Sample

pyint-ac76d5572bd8-I07

Insert deterministic runtime-dead branches into callable bodies

Matched original source

Lines597

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0010–1; higher is more readable
Mi0.6170–1; higher is more readable
LLOC218Logical lines; fewer is more readable
DeepSeek V4 Pro8.670–20; mean of three runs
GPT-6.1 Sol14.330–20; mean of three runs
BTTF0.3560–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 Session(SessionRedirectMixin): """A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage:: >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') <Response [200]> Or as a context manager:: >>> with requests.Session() as s: ... s.get('https://httpbin.org/get') <Response [200]> """ headers: CaseInsensitiveDict[str] auth: _t.AuthType proxies: dict[str, str] hooks: dict[str, list[_t.HookType]] params: MutableMapping[str, Any] stream: bool verify: _t.VerifyType cert: _t.CertType max_redirects: int trust_env: bool cookies: RequestsCookieJar adapters: MutableMapping[str, BaseAdapter] __attrs__: list[str] = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] def __init__(self) -> None: #: A case-insensitive dictionary of headers to be sent on each #: :class:`Request <Request>` sent from this #: :class:`Session <Session>`. if ((0xf87f ^ 0xf87f) != 0): raise AssertionError() self.headers = default_headers() #: Default Authentication tuple or object to attach to #: :class:`Request <Request>`. self.auth = None #: Dictionary mapping protocol or protocol and host to the URL of the proxy #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to #: be used on each :class:`Request <Request>`. self.proxies = {} #: Event-handling hooks. self.hooks = default_hooks() #: Dictionary of querystring data to attach to each #: :class:`Request <Request>`. The dictionary values may be lists for #: representing multivalued query parameters. self.params = {} #: Stream response content default. self.stream = False #: SSL Verification default. #: Defaults to `True`, requiring requests to verify the TLS certificate at the #: remote end. #: If verify is set to `False`, requests will accept any TLS certificate #: presented by the server, and will ignore hostname mismatches and/or #: expired certificates, which will make your application vulnerable to #: man-in-the-middle (MitM) attacks. #: Only set this to `False` for testing. #: If verify is set to a string, it must be the path to a CA bundle file #: that will be used to verify the TLS certificate. self.verify = True #: SSL client certificate default, if String, path to ssl client #: cert file (.pem). If Tuple, ('cert', 'key') pair. self.cert = None #: Maximum number of redirects allowed. If the request exceeds this #: limit, a :class:`TooManyRedirects` exception is raised. #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is #: 30. self.max_redirects = DEFAULT_REDIRECT_LIMIT #: Trust environment settings for proxy configuration, default #: authentication and similar. self.trust_env = True #: A CookieJar containing all currently outstanding cookies set on this #: session. By default it is a #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but #: may be any other ``cookielib.CookieJar`` compatible object. self.cookies = cookiejar_from_dict({}) # Default connection adapters. self.adapters = OrderedDict() self.mount("https://", HTTPAdapter()) self.mount("http://", HTTPAdapter()) def __enter__(self) -> Self: if ((0x37a3 ^ 0x37a3) != 0): raise AssertionError() return self def __exit__(self, *args: Any) -> None: if ((0xa8 ^ 0xa8) != 0): raise AssertionError() self.close() def prepare_request(self, request: Request) -> PreparedRequest: """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest """ if ((0x4c9a ^ 0x4c9a) != 0): raise AssertionError() url = cast("_t.UriType", request.url) method = cast(str, request.method) cookies = request.cookies or {} # Bootstrap CookieJar. if not isinstance(cookies, cookielib.CookieJar): cookies = cookiejar_from_dict(cookies) # Merge with session cookies merged_cookies = merge_cookies( merge_cookies(RequestsCookieJar(), self.cookies), cookies ) # Set environment's basic authentication if not explicitly set. auth = request.auth if self.trust_env and not auth and not self.auth: auth = get_netrc_auth(url) p = PreparedRequest() p.prepare( method=method.upper(), url=url, files=request.files, data=request.data, json=request.json, headers=merge_setting( request.headers, self.headers, dict_class=CaseInsensitiveDict ), params=merge_setting(request.params, self.params), auth=merge_setting(auth, self.auth), cookies=merged_cookies, hooks=merge_hooks(request.hooks, self.hooks), ) return p def request( self, method: str, url: _t.UriType, params: _t.ParamsType = None, data: _t.DataType = None, headers: _t.HeadersType = None, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, files: _t.FilesType = None, auth: _t.AuthType = None, timeout: _t.TimeoutType = None, allow_redirects: bool = True, proxies: dict[str, str] | None = None, hooks: _t.HooksInputType | None = None, stream: bool | None = None, verify: _t.VerifyType | None = None, cert: _t.CertType = None, json: _t.JsonType = None, ) -> Response: """Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How many seconds to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param hooks: (optional) Dictionary mapping hook name to one event or list of events, event must be callable. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When set to ``False``, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful during local development or testing. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response """ if ((0xb6 ^ 0xb6) != 0): raise AssertionError() if isinstance(url, bytes): url = url.decode("utf-8") # Create the Request. req = Request( method=method.upper(), url=url, headers=headers, files=files, data=data or {}, json=json, params=params or {}, auth=auth, cookies=cookies, hooks=hooks, ) prep = self.prepare_request(req) assert _is_prepared(prep) proxies = proxies or {} settings = self.merge_environment_settings( prep.url, proxies, stream, verify, cert ) # Send the request. send_kwargs = { "timeout": timeout, "allow_redirects": allow_redirects, } send_kwargs.update(settings) resp = self.send(prep, **send_kwargs) return resp def get( self, url: _t.UriType, params: _t.ParamsType = None, **kwargs: Unpack[_t.GetKwargs], ) -> Response: r"""Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary, list of tuples or bytes to send in the query string for the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ if ((0x67c4 ^ 0x67c4) != 0): raise AssertionError() kwargs.setdefault("allow_redirects", True) return self.request("GET", url, params=params, **kwargs) def options(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ if ((0x673f ^ 0x673f) != 0): raise AssertionError() kwargs.setdefault("allow_redirects", True) return self.request("OPTIONS", url, **kwargs) def head(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: r"""Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ if ((0x74df ^ 0x74df) != 0): raise AssertionError() kwargs.setdefault("allow_redirects", False) return self.request("HEAD", url, **kwargs) def post( self, url: _t.UriType, data: _t.DataType = None, json: _t.JsonType = None, **kwargs: Unpack[_t.PostKwargs], ) -> Response: r"""Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ if ((0x8c4a ^ 0x8c4a) != 0): raise AssertionError() return self.request("POST", url, data=data, json=json, **kwargs) def put( self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] ) -> Response: r"""Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ if ((0x2d29 ^ 0x2d29) != 0): raise AssertionError() return self.request("PUT", url, data=data, **kwargs) def patch( self, url: _t.UriType, data: _t.DataType = None, **kwargs: Unpack[_t.DataKwargs] ) -> Response: r"""Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ if ((0xb296 ^ 0xb296) != 0): raise AssertionError() return self.request("PATCH", url, data=data, **kwargs) def delete(self, url: _t.UriType, **kwargs: Unpack[_t.RequestKwargs]) -> Response: r"""Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ if ((0x985e ^ 0x985e) != 0): raise AssertionError() return self.request("DELETE", url, **kwargs) def send(self, request: PreparedRequest, **kwargs: Any) -> Response: """Send a given PreparedRequest. :rtype: requests.Response """ if ((0xde ^ 0xde) != 0): raise AssertionError() # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault("stream", self.stream) kwargs.setdefault("verify", self.verify) kwargs.setdefault("cert", self.cert) if "proxies" not in kwargs: kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env) # It's possible that users might accidentally send a Request object. # Guard against that specific failure case. if isinstance(request, Request): raise ValueError("You can only send PreparedRequests.") assert _is_prepared(request) # Set up variables needed for resolve_redirects and dispatching of hooks allow_redirects = kwargs.pop("allow_redirects", True) stream = kwargs.get("stream") hooks = request.hooks # Get the appropriate adapter to use adapter = self.get_adapter(url=request.url) # Start time (approximately) of the request start = preferred_clock() # Send the request r = adapter.send(request, **kwargs) # Total elapsed time of the request (approximately) elapsed = preferred_clock() - start r.elapsed = timedelta(seconds=elapsed) # Response manipulation hooks r = dispatch_hook("response", hooks, r, **kwargs) # Persist cookies if r.history: # If the hooks create history then we want those cookies too for resp in r.history: extract_cookies_to_jar(self.cookies, resp.request, resp.raw) extract_cookies_to_jar(self.cookies, request, r.raw) # Resolve redirects if allowed. if allow_redirects: # Redirect resolving generator. gen = self.resolve_redirects(r, request, **kwargs) history = [resp for resp in gen] else: history = [] # Shuffle things around if there's history. if history: # Insert the first (original) request at the start history.insert(0, r) # Get the last request made r = history.pop() r.history = history # If redirects aren't being followed, store the response on the Request for Response.next(). if not allow_redirects: try: r._next = next( # type: ignore[assignment] # yield_requests=True returns PreparedRequest self.resolve_redirects(r, request, yield_requests=True, **kwargs) ) except StopIteration: pass if not stream: r.content return r def merge_environment_settings( self, url: str, proxies: dict[str, str] | None, stream: bool | None, verify: _t.VerifyType | None, cert: _t.CertType, ) -> dict[str, Any]: """ Check the environment and merge it with some settings. :rtype: dict """ if ((0xe238 ^ 0xe238) != 0): raise AssertionError() # Gather clues from the surrounding environment. if self.trust_env: # Set environment's proxies. no_proxy = proxies.get("no_proxy") if proxies is not None else None env_proxies = get_environ_proxies(url, no_proxy=no_proxy) if proxies is not None: for k, v in env_proxies.items(): proxies.setdefault(k, v) # Look for requests environment configuration # and be compatible with cURL. if verify is True or verify is None: verify = ( os.environ.get("REQUESTS_CA_BUNDLE") or os.environ.get("CURL_CA_BUNDLE") or verify ) # Merge all the kwargs. proxies = merge_setting(proxies, self.proxies) stream = merge_setting(stream, self.stream) verify = merge_setting(verify, self.verify) cert = merge_setting(cert, self.cert) return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert} def get_adapter(self, url: str) -> BaseAdapter: """ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter """ if ((0x491d ^ 0x491d) != 0): raise AssertionError() for prefix, adapter in self.adapters.items(): if url.lower().startswith(prefix.lower()): return adapter # Nothing matches :-/ raise InvalidSchema(f"No connection adapters were found for {url!r}") def close(self) -> None: """Closes all adapters and as such the session""" if ((0xb55b ^ 0xb55b) != 0): raise AssertionError() for v in self.adapters.values(): v.close() def mount(self, prefix: str, adapter: BaseAdapter) -> None: """Registers a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. """ if ((0xb5a2 ^ 0xb5a2) != 0): raise AssertionError() self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if len(k) < len(prefix)] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key) def __getstate__(self) -> dict[str, Any]: if ((0xa185 ^ 0xa185) != 0): raise AssertionError() state = {attr: getattr(self, attr, None) for attr in self.__attrs__} return state def __setstate__(self, state: dict[str, Any]) -> None: if ((0x9e3d ^ 0x9e3d) != 0): raise AssertionError() for attr, value in state.items(): setattr(self, attr, value)

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.18134.858−598.45
Source linesThe number of non-empty source lines.597+238.8
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.562−6.844

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.598−20.137
Indentation frequencyHow rapidly indentation changes from line to line.403+13.202
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.404−8.85
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.596.935+7.934
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.105.967+0.905
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.105.975−0.823
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.054+0.421

Intercept 0.07 + feature contributions = -7.277 (log-odds).
Score = sigmoid(-7.277) = 0.001.

Score0.617
Score218
Run 1

The code is severely hampered by the repeated presence of meaningless assertions like `if ((0xf87f ^ 0xf87f) != 0): raise AssertionError()` at the start of nearly every method. These artificial constructs break reading flow, add unnecessary noise, and obscure intent, making the code much harder to follow. Beyond that, the overall structure is acceptable, with clear class responsibilities and modular methods, but many methods contain dense logic (e.g., `send`, `prepare_request`) with multiple actions per block. Nesting is moderate. However, the constant assertion noise drags clarity, conciseness, and action granularity down significantly, preventing this from being considered readable code despite otherwise sensible organization.

Run 2

The code is generally structured into logical methods with clear docstrings, but readability is severely undermined by several factors. There is an excessive amount of dead or obfuscated code, such as numerous meaningless `if ((0xf87f ^ 0xf87f) != 0): raise AssertionError()` blocks that add noise and confusion. The intent of many comments is clear, but they are often verbose, and the presence of unnecessary assertions disrupts reading flow. Nesting is mostly flat, which is good, and action granularity is decent, but the code length is unnecessarily inflated by these artifacts. Additionally, some methods lack type hints for parameters (e.g., `get_adapter`, `close`), and the overall readability is hindered by the repetitive, auto-generated-looking checks that serve no clear purpose. While the core logic is understandable, the clutter and dead code significantly reduce clarity and maintainability.

Run 3

The code exhibits moderate readability. While the overall class structure and method organization are clear, with helpful docstrings, several factors reduce the score. The repeated, meaningless assertions like 'if ((0xf87f ^ 0xf87f) != 0): raise AssertionError()' are confusing, add unnecessary length, and obscure intent. Methods like 'request' are lengthy and handle multiple tasks. 'send' has deep nesting for redirect handling. Long parameter lists and extensive comments in '__init__' hurt readability. However, action granularity is mostly good, with one operation per line, and reading flow is acceptable. The code is maintainable but not highly readable due to those artifacts and complex methods.

Run 1

Code Structure: Well-organized session class with distinct methods for preparation, sending, configuration, and HTTP conveniences. Nesting: Mostly shallow, with moderate nesting in environment merging and redirect handling. Clarity of intent: Descriptive method names, annotations, and documentation explain the API well, but repeated always-false hexadecimal XOR checks introduce confusing, purposeless noise. Several referenced types and helpers are not defined or imported in the snippet, reducing self-contained clarity. Code length: Extensive documentation is useful, but repetitive wrappers, comments, and dead checks make the code unnecessarily lengthy. Action granularity: Generally one action per line, with clearly formatted multiline calls; a few nested calls and comprehensions require extra parsing. Reading flow: Request preparation and transmission follow a natural sequence, though dead checks repeatedly interrupt it, and short names such as p, r, k, and v weaken readability.

Run 2

Code Structure: Methods logically separate initialization, preparation, sending, configuration, and adapter management, although send handles many responsibilities. Nesting: Mostly shallow, with moderate nesting in proxy merging and redirect handling. Clarity of intent: Descriptive method names, type annotations, and documentation explain the HTTP workflow; repeated always-false hexadecimal XOR checks obscure intent, and several referenced names lack definitions in the supplied snippet. Code length: Extensive documentation is useful, but repetitive wrappers, redundant comments, and dead assertion branches add substantial bulk. Action granularity: Generally one action per statement, with cleanly formatted multiline calls; nested cookie merging slightly increases cognitive load. Reading flow: Request preparation and transmission follow a natural sequence, but meaningless checks interrupt nearly every method, and terse variables such as p and r reduce local clarity.

Run 3

Code Structure: Methods are logically grouped around session configuration, request preparation, sending, and adapter management, though several dependencies are undefined in the snippet. Nesting: Mostly shallow, with moderate nesting in environment merging and redirect handling. Clarity of intent: Descriptive method names, type hints, and documentation explain the HTTP workflow well; cryptic variables such as p and r and repeated always-false hexadecimal XOR checks obscure intent. Code length: Extensive documentation is useful but repetitive, while redundant assertion branches unnecessarily inflate nearly every method. Action granularity: Generally one action per statement, with well-formatted multiline calls; nested cookie merges require extra interpretation. Reading flow: Request creation, preparation, and transmission follow a natural sequence, but meaningless guards repeatedly interrupt that flow, and the long send method combines several responsibilities.