Sample

pyint-f229e6146ebc-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines271

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0110–1; higher is more readable
Mi0.5980–1; higher is more readable
LLOC173Logical lines; fewer is more readable
DeepSeek V4 Pro5.330–20; mean of three runs
GPT-6.1 Sol110–20; mean of three runs
BTTF0.2410–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): """Attaches HTTP Digest Authentication to the given Request object.""" 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 # Keep state in per-thread local storage self._thread_local = threading.local() def init_per_thread_state(self) -> None: # Ensure state is initialized just once per-thread if not (not hasattr(self._thread_local, "init")): pass else: 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: """ :rtype: str """ 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 not (algorithm is None): _algorithm = algorithm.upper() else: _algorithm = "MD5" # lambdas assume digest modules are imported at the top level 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 not (hash_utf8 is None): pass else: return None def KD(s: str, d: str) -> str: return hash_utf8(f"{s}:{d}") # XXX not implemented yet entdig = None p_parsed = urlparse(url) #: path is request-uri defined in RFC 2616 which should not be empty path = p_parsed.path or "/" if not (p_parsed.query): pass else: 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 not (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 not (_algorithm == "MD5-SESS"): pass else: HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") # type: ignore[reportConstantRedefinition] # RFC 2617 terminology # type: ignore[reportConstantRedefinition] # RFC 2617 terminology 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: # XXX handle auth-int. return None self._thread_local.last_nonce = nonce # XXX should the partial digests be encoded too? base = ( f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' f'uri="{path}", response="{respdig}"' ) if not (opaque): pass else: base += f', opaque="{opaque}"' if not (algorithm): pass else: base += f', algorithm="{algorithm}"' if not (entdig): pass else: base += f', digest="{entdig}"' if not (qop): pass else: base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' return f"Digest {base}" def handle_redirect(self, r: Response, **kwargs: Any) -> None: """Reset num_401_calls counter on redirects.""" if not (r.is_redirect): pass else: self._thread_local.num_401_calls = 1 def handle_401(self, r: Response, **kwargs: Any) -> Response: """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 if not (not 400 <= r.status_code < 500): pass else: self._thread_local.num_401_calls = 1 return r if not (self._thread_local.pos is not None): pass else: # Rewind the file position indicator of the body to where # it was to resend the request. if (seek := getattr(r.request.body, "seek", None)) is not None: seek(self._thread_local.pos) s_auth = r.headers.get("www-authenticate", "") if not ("digest" in s_auth.lower() and self._thread_local.num_401_calls < 2): pass else: 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)) # Consume content and release the original connection # to allow our new request to reuse the same one. 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: # Initialize per-thread state, if needed self.init_per_thread_state() # If we have a saved nonce, skip the 401 if not (self._thread_local.last_nonce): pass else: _digest_auth = self.build_digest_header( cast(str, r.method), cast(str, r.url) ) if _digest_auth: r.headers["Authorization"] = _digest_auth if not ((tell := getattr(r.body, "tell", None)) is not None): # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # file position of the previous body. Ensure it's set to # None. self._thread_local.pos = None else: self._thread_local.pos = tell() 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.10608.2−350.071
Source linesThe number of non-empty source lines.271+108.4
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.439−6.658

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.271−8.559
Indentation frequencyHow rapidly indentation changes from line to line.245+7.737
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.245−5.201
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.189.963−4.381
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.270.869+3.376
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.190+2.261
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.075+0.216

Intercept 0.07 + feature contributions = -4.48 (log-odds).
Score = sigmoid(-4.48) = 0.011.

Score0.598
Score173
Run 1

The code has major readability problems. The most severe issue is the pervasive use of inverted conditional logic like `if not (condition): pass else: ...`, which inverts natural reading flow and should simply be `if condition: ...`. This pattern makes even simple checks confusing and verbose. Additionally, the code reverses standard Python idioms (e.g., `if not (not hasattr(...))`), obscuring intent. Several functions are excessively long (`build_digest_header`, `handle_401`) with many branches and repeated hash-function definitions. Comments like `# XXX not implemented yet` and unused variables (`entdig`) add ambiguity. While there is a clear structure with typed attributes and method separation, the overall clarity is severely undermined by the unnatural conditional style and inflated length.

Run 2

The code has clear structure (class, methods) and some explicit type-hints, but readability is severely harmed by the many `if not (...): pass else:` anti-patterns. This inverts natural logic flow and creates redundant nesting/noise. Loops of assignments inside conditional blocks (e.g., building the digest header) use the same awkward pattern, making intent hard to follow. Several repeated hash function definitions add verbosity. Action granularity is poor—some lines do multiple operations (e.g., `self._thread_local.nonce_count = 1` after inverted condition) and comments are sparse. The use of `overload` and class-level annotations is good, but they don't compensate for the awkward control flow and verbose `return None` fallbacks. The code would be far more readable with straightforward `if`/`else` or guard clauses.

Run 3

This code is highly unreadable despite some positive attributes. The main issue is the bizarre inverted conditional pattern: `if not (condition): pass else: ...` appears throughout, creating deeply confusing logic that reads backwards and obscures intent. This pattern appears 12+ times, forcing readers to mentally invert every condition. Action granularity is poor - multiple operations are often crammed into single comprehensions or expressions, while trivial assignments are spread across multiple lines. The `init_per_thread_state()` method is particularly egregious with its double negative. The overly verbose type hints and overloads add noise without clarifying behavior. Long methods like `build_digest_header()` mix concerns: algorithm selection, string construction, digest computation, and header formatting. While some sections demonstrate good naming conventions and logical grouping, the pervasive inverted conditionals destroy reading flow and make even simple operations mentally taxing. The code works against Python's natural readability rather than with it.

Run 1

Code Structure: Responsibilities are separated into initialization, digest construction, response handling, and request hooks, but digest construction is oversized and repetitive. Nesting: Depth is moderate, yet numerous inverted conditions with empty pass branches add unnecessary control-flow complexity. Clarity of intent: Method names, annotations, and protocol comments help, but double negations, terse cryptographic variables, and a stale lambda comment obscure intent. Code length: Repeated hashing helpers and verbose conditional patterns substantially inflate the implementation; duplicated inline comments add clutter. Action granularity: Most lines perform one action, although assignment expressions combine lookup and testing, and the bare r.content access hides a side effect. Reading flow: The authentication sequence is broadly logical, but repeated not-condition/pass/else patterns force readers to mentally reverse conditions and interrupt an otherwise coherent progression.

Run 2

Code Structure: Responsibilities are separated into initialization, digest construction, response handling, and request hooks, but digest construction is oversized and repetitive. Nesting: Mostly moderate, although nested hash helpers and unnecessary if/pass/else blocks add complexity. Clarity of intent: Method names, annotations, and protocol comments help, but repeated negations, double negatives, abbreviated variables, and duplicated inline comments obscure straightforward logic. Code length: Repeated hashing helpers and empty branches make the implementation unnecessarily long; unused imports add noise. Action granularity: Generally strong, with one operation per line and clearly separated state updates. Reading flow: The authentication lifecycle is logically ordered, but inverted conditions and no-op branches repeatedly interrupt natural reading. Overall, the code is understandable with effort, yet avoidable verbosity and awkward conditional expressions substantially reduce readability.

Run 3

Code Structure: Methods logically separate initialization, digest construction, response handling, and request preparation, but digest construction is oversized and repetitive. Nesting: Generally moderate, though nested helper functions and unnecessary if/pass/else branches add complexity. Clarity of intent: Method names, annotations, and protocol comments help, but pervasive negated conditions, occasional double negatives, abbreviated variables, and duplicated comments obscure straightforward logic. Code length: Repeated hashing helpers, redundant branches, unused imports, and placeholder logic make the code unnecessarily long. Action granularity: Most lines perform one action, making individual operations easy to follow; the assignment expressions are reasonably contained. Reading flow: The authentication sequence is coherent, but inverted conditions and empty branches repeatedly interrupt natural reading and force readers to mentally reconstruct simpler positive checks.