Sample

pyint-bef4632bde49-I01

Remove comments and docstrings

Matched original source

Lines239

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0650–1; higher is more readable
Mi0.7410–1; higher is more readable
LLOC156Logical lines; fewer is more readable
DeepSeek V4 Pro12.330–20; mean of three runs
GPT-6.1 Sol140–20; mean of three runs
BTTF0.310–1; higher is more readable

Views

Source code

from __future__ import annotations import hashlib import os import re import threading import time import warnings from base64 import b64encode from typing import TYPE_CHECKING, Any, Final, cast, overload from ._internal_utils import to_native_string from .compat import basestring, str, urlparse from .cookies import extract_cookies_to_jar from .utils import parse_dict_header class HTTPDigestAuth(AuthBase): username: bytes | str password: bytes | str _thread_local: threading.local last_nonce: str nonce_count: int chal: dict[str, str] pos: int | None num_401_calls: int | None @overload def __init__(self, username: str, password: str) -> None: ... @overload def __init__(self, username: bytes, password: bytes) -> None: ... def __init__(self, username: bytes | str, password: bytes | str) -> None: self.username = username self.password = password self._thread_local = threading.local() def init_per_thread_state(self) -> None: if not hasattr(self._thread_local, "init"): self._thread_local.init = True self._thread_local.last_nonce = "" self._thread_local.nonce_count = 0 self._thread_local.chal = {} self._thread_local.pos = None self._thread_local.num_401_calls = None def build_digest_header(self, method: str, url: str) -> str | None: realm = self._thread_local.chal["realm"] nonce = self._thread_local.chal["nonce"] qop = self._thread_local.chal.get("qop") algorithm = self._thread_local.chal.get("algorithm") opaque = self._thread_local.chal.get("opaque") hash_utf8 = None if algorithm is None: _algorithm = "MD5" else: _algorithm = algorithm.upper() if _algorithm == "MD5" or _algorithm == "MD5-SESS": def md5_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.md5(x, usedforsecurity=False).hexdigest() hash_utf8 = md5_utf8 elif _algorithm == "SHA": def sha_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha1(x, usedforsecurity=False).hexdigest() hash_utf8 = sha_utf8 elif _algorithm == "SHA-256": def sha256_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha256(x, usedforsecurity=False).hexdigest() hash_utf8 = sha256_utf8 elif _algorithm == "SHA-512": def sha512_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha512(x, usedforsecurity=False).hexdigest() hash_utf8 = sha512_utf8 if hash_utf8 is None: return None def KD(s: str, d: str) -> str: return hash_utf8(f"{s}:{d}") entdig = None p_parsed = urlparse(url) path = p_parsed.path or "/" if p_parsed.query: path += f"?{p_parsed.query}" A1 = f"{self.username}:{realm}:{self.password}" A2 = f"{method}:{path}" HA1 = hash_utf8(A1) HA2 = hash_utf8(A2) if nonce == self._thread_local.last_nonce: self._thread_local.nonce_count += 1 else: self._thread_local.nonce_count = 1 ncvalue = f"{self._thread_local.nonce_count:08x}" s = str(self._thread_local.nonce_count).encode("utf-8") s += nonce.encode("utf-8") s += time.ctime().encode("utf-8") s += os.urandom(8) cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:16] if _algorithm == "MD5-SESS": HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") if not qop: respdig = KD(HA1, f"{nonce}:{HA2}") elif qop == "auth" or "auth" in qop.split(","): noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" respdig = KD(HA1, noncebit) else: return None self._thread_local.last_nonce = nonce base = ( f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' f'uri="{path}", response="{respdig}"' ) if opaque: base += f', opaque="{opaque}"' if algorithm: base += f', algorithm="{algorithm}"' if entdig: base += f', digest="{entdig}"' if qop: base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' return f"Digest {base}" def handle_redirect(self, r: Response, **kwargs: Any) -> None: if r.is_redirect: self._thread_local.num_401_calls = 1 def handle_401(self, r: Response, **kwargs: Any) -> Response: if not 400 <= r.status_code < 500: self._thread_local.num_401_calls = 1 return r if self._thread_local.pos is not None: if (seek := getattr(r.request.body, "seek", None)) is not None: seek(self._thread_local.pos) s_auth = r.headers.get("www-authenticate", "") if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2: self._thread_local.num_401_calls += 1 pat = re.compile(r"digest ", flags=re.IGNORECASE) self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1)) r.content r.close() prep = r.request.copy() cookie_jar = cast("CookieJar", prep._cookies) extract_cookies_to_jar(cookie_jar, r.request, r.raw) prep.prepare_cookies(cookie_jar) _digest_auth = self.build_digest_header( cast(str, prep.method), cast(str, prep.url) ) if _digest_auth: prep.headers["Authorization"] = _digest_auth _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r self._thread_local.num_401_calls = 1 return r def __call__(self, r: PreparedRequest) -> PreparedRequest: self.init_per_thread_state() if self._thread_local.last_nonce: _digest_auth = self.build_digest_header( cast(str, r.method), cast(str, r.url) ) if _digest_auth: r.headers["Authorization"] = _digest_auth if (tell := getattr(r.body, "tell", None)) is not None: self._thread_local.pos = tell() else: self._thread_local.pos = None r.register_hook("response", self.handle_401) r.register_hook("response", self.handle_redirect) self._thread_local.num_401_calls = 1 return r def __eq__(self, other: object) -> bool: return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] ) def __ne__(self, other: Any) -> bool: return not self == other

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.9857.17−325.287
Source linesThe number of non-empty source lines.239+95.6
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.411−6.617

Intercept 8.87 + feature contributions = -227.433 (log-odds).
Score = sigmoid(-227.433) = 0.

Feature contributions

FeatureValueContribution
(log-odds)
Indentation frequencyHow rapidly indentation changes from line to line.239+7.53
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.240−7.461
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.239−5.063
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.238.884+2.929
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.0−0.804
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.089+0.075
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.84.963+0.067

Intercept 0.07 + feature contributions = -2.658 (log-odds).
Score = sigmoid(-2.658) = 0.065.

Score0.741
Score156
Run 1

The code exhibits reasonable structure with clear class and method separation, but suffers from several readability issues. The class has excessive blank lines and redundant comments, making it feel fragmented. There is moderate nesting in methods like `build_digest_header`, which uses multiple conditional branches for algorithm selection and qop handling. Action granularity is mixed—some lines attempt multiple operations (e.g., `seek(self._thread_local.pos)`), while others are unnecessarily verbose. Clarity of intent is inconsistent; methods like `handle_401` and `__call__` lack explanatory context for their complex logic. The use of walrus operators and type casting adds cognitive load. Reading flow is disrupted by the large number of inline comments that state the obvious rather than clarify non-obvious behavior. Overall, the code is functional but not optimized for quick comprehension.

Run 2

The code has clear type hints and a logical class structure, but readability suffers significantly from excessive blank lines and whitespace (e.g., multiple consecutive blank lines between every statement), which disrupts reading flow. Nested functions (md5_utf8, sha_utf8, KD) are defined conditionally inside a larger method, increasing cognitive load. The build_digest_header method is very long, packs multiple logical steps (algorithm selection, path construction, nonce handling, header assembly), and mixes string concatenation with f-strings. Some variable names are cryptic (KD, A1, HA1), and the heavy use of casts (cast(str, prep.method)) obscures intent. The handle_401 method is deeply nested and mixes authentication logic with response handling. While each line mostly performs one action, the overall structure feels cluttered due to inconsistent spacing and lack of separation between high-level steps.

Run 3

The code demonstrates generally good readability with clear class structure and organized methods. The nesting is mostly flat, and each function handles a distinct concern. Type hints and docstrings enhance clarity, though some complex logic in build_digest_header could be extracted for better comprehension. The use of inline comments explains non-obvious behavior like thread-local state initialization and body position tracking. Action granularity is appropriate, with most lines performing single operations. However, some methods like build_digest_header are quite long and contain multiple nested function definitions for different hash algorithms, adding complexity. The flow between methods is logical, though the abbreviation 'KD' for key derivation may not be immediately intuitive. Overall, the code is maintainable for developers familiar with HTTP authentication protocols, but could benefit from breaking down the longest methods and providing more context for cryptographic operations.

Run 1

Code Structure: Methods logically separate initialization, digest construction, response handling, and request preparation, but build_digest_header combines several responsibilities. Nesting: Mostly shallow, with moderate nesting in algorithm-specific helpers and retry handling; early returns simplify control flow. Clarity of intent: Method names and type hints help, but cryptographic abbreviations, terse variables such as s and _r, undocumented thread-local state, and the standalone r.content expression require background knowledge. Code length: Repeated hashing helpers, unused imports, an inactive entdig branch, and excessive blank lines add avoidable bulk. Action granularity: Generally one action per line, with readable multiline expressions; assignment expressions slightly increase cognitive load. Reading flow: The authentication sequence is coherent, but inconsistent whitespace, repetitive attribute access, and missing explanations for protocol details interrupt comprehension.

Run 2

Code Structure: Methods separate initialization, digest construction, response handling, and request setup logically, but digest construction combines several responsibilities. Nesting: Mostly shallow conditionals and early returns; nested hash helpers and retry logic add moderate complexity. Clarity of intent: Method names and type annotations help, but abbreviated variables such as KD, A1, s, and _r, undocumented protocol details, and implicit thread-local state obscure intent. Code length: Repeated hash wrappers, unused imports, excessive blank lines, and the inactive entdig branch add unnecessary bulk. Action granularity: Generally one operation per line, with only modest complexity from assignment expressions and compound conditions. Reading flow: Authentication proceeds in a sensible sequence, but sparse explanations, inconsistent whitespace, and state dependencies across methods interrupt comprehension.

Run 3

Code Structure: Responsibilities are separated into initialization, header construction, response handling, and request hooks, but build_digest_header combines several substantial tasks. Nesting: Mostly shallow conditionals and early returns keep complexity manageable; nested hash helpers and retry logic add some depth. Clarity of intent: Method names and type annotations help, but cryptographic abbreviations, terse variables, implicit thread-local state, and absent explanatory comments obscure protocol details. Code length: Repeated hash wrappers, unused imports, an unused digest placeholder, and excessive blank lines make the code longer than necessary. Action granularity: Statements generally perform one action per line, making operations easy to inspect, though the standalone r.content access has an unexplained side effect. Reading flow: Authentication steps follow a reasonably natural sequence, but inconsistent whitespace, repeated thread-local references, and underspecified dependencies interrupt the flow.