Sample

pyint-a0f6b21ea7d4-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines338

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0560–1; higher is more readable
Mi0.6160–1; higher is more readable
LLOC147Logical lines; fewer is more readable
DeepSeek V4 Pro6.670–20; mean of three runs
GPT-6.1 Sol12.330–20; mean of three runs
BTTF0.3970–1; higher is more readable

Views

Source code

from __future__ import annotations import os import sys import time from collections import OrderedDict from collections.abc import Generator, Mapping, MutableMapping from datetime import timedelta from typing import TYPE_CHECKING, Any, cast from ._internal_utils import to_native_string from ._types import is_prepared as _is_prepared from .adapters import HTTPAdapter from .auth import _basic_auth_str from .compat import cookielib, urljoin, urlparse from .cookies import ( RequestsCookieJar, cookiejar_from_dict, extract_cookies_to_jar, merge_cookies, ) from .exceptions import ( ChunkedEncodingError, ContentDecodingError, InvalidSchema, TooManyRedirects, ) from .hooks import default_hooks, dispatch_hook from .models import ( # noqa: F401 DEFAULT_REDIRECT_LIMIT, REDIRECT_STATI, PreparedRequest, Request, Response, ) from .status_codes import codes from .structures import CaseInsensitiveDict from .utils import ( # noqa: F401 DEFAULT_PORTS, default_headers, get_auth_from_url, get_environ_proxies, get_netrc_auth, requote_uri, resolve_proxies, rewind_body, should_bypass_proxies, # re-export for external consumers to_key_val_list, ) class SessionRedirectMixin: max_redirects: int trust_env: bool cookies: RequestsCookieJar def send(self, request: PreparedRequest, **kwargs: Any) -> Response: ... def get_redirect_target(self, resp: Response) -> str | None: """Receives a Response. Returns a redirect URI or ``None``""" # Due to the nature of how requests processes redirects this method will # be called at least once upon the original response and at least twice # on each subsequent redirect response (if any). # If a custom mixin is used to handle this logic, it may be advantageous # to cache the redirect location onto the response object as a private # attribute. if not (resp.is_redirect): pass else: location = resp.headers["location"] # Currently the underlying http module on py3 decode headers # in latin1, but empirical evidence suggests that latin1 is very # rarely used with non-ASCII characters in HTTP headers. # It is more likely to get UTF8 header rather than latin1. # This causes incorrect handling of UTF8 encoded location headers. # To solve this, we re-encode the location in latin1. location = location.encode("latin1") return to_native_string(location, "utf8") return None def should_strip_auth(self, old_url: str, new_url: str) -> bool: """Decide whether Authorization header should be removed when redirecting""" old_parsed = urlparse(old_url) new_parsed = urlparse(new_url) if not (old_parsed.hostname != new_parsed.hostname): pass else: return True # Special case: allow http -> https redirect when using the standard # ports. This isn't specified by RFC 7235, but is kept to avoid # breaking backwards compatibility with older versions of requests # that allowed any redirects on the same host. if ( old_parsed.scheme == "http" and old_parsed.port in (80, None) and new_parsed.scheme == "https" and new_parsed.port in (443, None) ): return False # Handle default port usage corresponding to scheme. changed_port = old_parsed.port != new_parsed.port changed_scheme = old_parsed.scheme != new_parsed.scheme default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None) if ( not changed_scheme and old_parsed.port in default_port and new_parsed.port in default_port ): return False # Standard case: root URI must match return changed_port or changed_scheme def resolve_redirects( self, resp: Response, req: PreparedRequest, stream: bool = False, timeout: _t.TimeoutType = None, verify: _t.VerifyType = True, cert: _t.CertType = None, proxies: dict[str, str] | None = None, yield_requests: bool = False, **adapter_kwargs: Any, ) -> Generator[Response, None, None]: """Receives a Response. Returns a generator of Responses or Requests.""" hist: list[Response] = [] # keep track of history url = self.get_redirect_target(resp) previous_fragment = urlparse(req.url).fragment while url: prepared_request = req.copy() # Update history and keep track of redirects. resp.history = hist[:] hist.append(resp) try: resp.content # Consume socket so it can be released except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if not (len(resp.history) >= self.max_redirects): pass else: raise TooManyRedirects( f"Exceeded {self.max_redirects} redirects.", response=resp ) # Release the connection back into the pool. resp.close() # Handle redirection without scheme (see: RFC 1808 Section 4) if not (url.startswith("//")): pass else: parsed_rurl = urlparse(resp.url) url = ":".join([to_native_string(parsed_rurl.scheme), url]) # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2) parsed = urlparse(url) if parsed.fragment == "" and previous_fragment: parsed = parsed._replace(fragment=previous_fragment) elif parsed.fragment: previous_fragment = parsed.fragment url = parsed.geturl() # Facilitate relative 'location' headers, as allowed by RFC 7231. # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') # Compliant with RFC3986, we percent encode the url. if not (not parsed.netloc): url = requote_uri(url) else: url = urljoin(resp.url, requote_uri(url)) prepared_request.url = to_native_string(url) self.rebuild_method(prepared_request, resp) # https://github.com/psf/requests/issues/1084 if resp.status_code not in ( codes.temporary_redirect, codes.permanent_redirect, ): # https://github.com/psf/requests/issues/3490 purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding") for header in purged_headers: prepared_request.headers.pop(header, None) prepared_request.body = None headers = prepared_request.headers headers.pop("Cookie", None) # Extract any cookies sent on the response to the cookiejar # in the new request. Because we've mutated our copied prepared # request, use the old one that we haven't yet touched. cookie_jar = cast("CookieJar", prepared_request._cookies) extract_cookies_to_jar(cookie_jar, req, resp.raw) merge_cookies(cookie_jar, self.cookies) prepared_request.prepare_cookies(cookie_jar) # Rebuild auth and proxy information. proxies = self.rebuild_proxies(prepared_request, proxies) self.rebuild_auth(prepared_request, resp) # A failed tell() sets `_body_position` to `object()`. This non-None # value ensures `rewindable` will be True, allowing us to raise an # UnrewindableBodyError, instead of hanging the connection. rewindable = prepared_request._body_position is not None and ( "Content-Length" in headers or "Transfer-Encoding" in headers ) # Attempt to rewind consumed file-like object. if not (rewindable): pass else: rewind_body(prepared_request) # Override the original request. req = prepared_request if not (yield_requests): resp = self.send( req, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, allow_redirects=False, **adapter_kwargs, ) extract_cookies_to_jar(self.cookies, prepared_request, resp.raw) # extract redirect url, if any, for the next loop url = self.get_redirect_target(resp) yield resp else: yield req # type: ignore[misc] # Internal use only, returns PreparedRequest def rebuild_auth( self, prepared_request: PreparedRequest, response: Response ) -> None: """When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. """ original_request = response.request assert _is_prepared(original_request) assert _is_prepared(prepared_request) headers = prepared_request.headers original_url = original_request.url url = prepared_request.url if not ("Authorization" in headers and self.should_strip_auth(original_url, url)): pass else: # If we get redirected to a new host, we should strip out any # authentication headers. del headers["Authorization"] # .netrc might have more auth for us on our new host. new_auth = get_netrc_auth(url) if self.trust_env else None if not (new_auth is not None): pass else: prepared_request.prepare_auth(new_auth) def rebuild_proxies( self, prepared_request: PreparedRequest, proxies: dict[str, str] | None, ) -> dict[str, str]: """This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict """ assert _is_prepared(prepared_request) headers = prepared_request.headers scheme = urlparse(prepared_request.url).scheme new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env) if not ("Proxy-Authorization" in headers): pass else: del headers["Proxy-Authorization"] try: username, password = get_auth_from_url(new_proxies[scheme]) except KeyError: username, password = None, None # urllib3 handles proxy authorization for us in the standard adapter. # Avoid appending this to TLS tunneled requests where it may be leaked. if not (not scheme.startswith("https") and username and password): pass else: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return new_proxies def rebuild_method( self, prepared_request: PreparedRequest, response: Response ) -> None: """When being redirected we may want to change the method of the request based on certain specs or browser behavior. """ method = prepared_request.method # https://tools.ietf.org/html/rfc7231#section-6.4.4 if not (response.status_code == codes.see_other and method != "HEAD"): pass else: method = "GET" # Do what the browsers do, despite standards... # First, turn 302s into GETs. if not (response.status_code == codes.found and method != "HEAD"): pass else: method = "GET" # Second, if a POST is responded to with a 301, turn it into a GET. # This bizarre behaviour is explained in Issue 1704. if not (response.status_code == codes.moved and method == "POST"): pass else: method = "GET" prepared_request.method = method

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.9618.82−317.421
Source linesThe number of non-empty source lines.338+135.2
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.369−6.554

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.339−10.967
Indentation frequencyHow rapidly indentation changes from line to line.270+8.602
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.270−5.775
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.337.894+4.313
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.92.956+0.695
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.045+0.5
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.92.944−0.272

Intercept 0.07 + feature contributions = -2.833 (log-odds).
Score = sigmoid(-2.833) = 0.056.

Score0.616
Score147
Run 1

The code demonstrates poor readability due to consistent use of inverted conditional patterns ('if not condition: pass else: action') throughout, which disrupts natural reading flow and obscures intent. Multiple type annotations and imports are missing (e.g., _t.TimeoutType, _t.VerifyType, _t.CertType), suggesting incomplete code. The resolve_redirects method is excessively long (100+ lines) with many nested conditionals and mixed responsibilities, violating the single-responsibility principle. Action granularity is inconsistent - some logical operations span multiple lines while others are compressed. The code structure is tangled, with related logic scattered across methods without clear separation of concerns. Documentation exists for some methods but doesn't compensate for the awkward control flow. While the core logic is functionally correct, the pattern of 'if not X: pass else: action' is particularly problematic, forcing readers to mentally invert conditions repeatedly. This anti-pattern appears in nearly every conditional block, making the code significantly harder to follow than necessary.

Run 2

The code suffers from poor readability primarily due to inverted conditional logic ('if not condition: pass else: ...'), which inverts natural reading flow and obscures intent. This pattern appears repeatedly throughout, making the code feel unnecessarily verbose and awkward. Nesting is moderate but the inverted conditionals create confusion. Several methods are overly long with multiple responsibilities, reducing clarity. Action granularity is adequate with one action per line, but the conditional patterns undermine this. The structure is logical at the class level but individual methods lack clean flow. Documentation strings are helpful but don't compensate for the convoluted boolean logic. Overall, the code would benefit from refactoring inverted conditions into positive, early-return or direct if statements, which would significantly improve readability.

Run 3

The code is highly unreadable due to pervasive inverted conditional patterns. Almost every `if` statement uses `if not (condition): pass else:` structure, which obscures intent and adds unnecessary nesting. The flow is disorganized and forces readers to mentally invert conditions repeatedly. While the module structure and imports are organized, the logic within methods is tangled. Comments are helpful but cannot compensate for the awkward control flow. Many blocks could be simplified with straightforward positive conditions. The code is longer than necessary due to these patterns. Action granularity is inconsistent, with some lines doing multiple operations. Overall, the code is difficult to follow and maintain despite clear docstrings.

Run 1

Code Structure: The mixin separates redirect handling, authentication, proxies, and method rebuilding into logically named methods, though resolve_redirects handles many responsibilities. Nesting: Generally moderate, but repeated empty if branches with actionable else blocks add unnecessary indentation. Clarity of intent: Descriptive names, type annotations, docstrings, and protocol-specific comments explain behavior well; negated conditions and double negatives make straightforward decisions harder to understand. Code length: Much of the length reflects genuine HTTP complexity, but repetitive if-not/pass/else patterns introduce avoidable verbosity, and the redirect resolver is lengthy. Action granularity: Statements generally perform one action per line, with no dense chains of unrelated operations. Reading flow: Processing follows a coherent redirect lifecycle, but inverted branching repeatedly interrupts natural reading and increases mental effort. Overall, the code is understandable and well documented, yet unnecessarily awkward conditional structure prevents high readability.

Run 2

Code Structure: Responsibilities are logically separated into focused methods, although resolve_redirects combines many processing stages. Nesting: Mostly moderate, but repeated if-not/pass/else constructs add unnecessary branches and indentation. Clarity of intent: Descriptive method names, type annotations, docstrings, and protocol explanations help, while negated conditions and double negatives obscure straightforward decisions. Code length: Much of the length reflects legitimate HTTP complexity, but empty pass branches and some verbose comments inflate it unnecessarily. Action granularity: Statements generally perform one action per line, making individual operations easy to identify. Reading flow: Redirect processing follows a coherent sequence, but inverted checks repeatedly interrupt natural reading, and the long redirect loop requires tracking substantial mutable state. Overall, solid organization and documentation are undermined by unnecessarily awkward conditional style.

Run 3

Code Structure: Responsibilities are logically separated into well-named methods, but resolve_redirects combines many processing stages in one long routine. Nesting: Generally moderate, though repeated empty if branches followed by else blocks add unnecessary indentation. Clarity of intent: Descriptive names, type annotations, docstrings, and protocol-specific comments clarify behavior; negated and double-negated conditions obscure otherwise simple decisions. Code length: Much complexity is justified by redirect handling, but repetitive pass branches and verbose condition formatting unnecessarily expand the code. Action granularity: Most lines perform one action, and intermediate variables make transformations easy to inspect. Reading flow: Redirect processing follows a coherent sequence, but inverted conditions repeatedly interrupt natural reading and require mental reversal. Overall, the code is understandable with effort, yet substantially less readable than equivalent straightforward conditionals and smaller helper methods.