Sample

pyint-15e77a98ba05-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines314

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.8760–1; higher is more readable
Mi0.5980–1; higher is more readable
LLOC153Logical lines; fewer is more readable
DeepSeek V4 Pro7.670–20; mean of three runs
GPT-6.1 Sol130–20; mean of three runs
BTTF0.3980–1; higher is more readable

Views

Source code

from __future__ import annotations import calendar import copy import time from collections.abc import Iterator, MutableMapping from http.cookiejar import Cookie, CookieJar, CookiePolicy from typing import TYPE_CHECKING, Any, TypeVar, overload from ._internal_utils import to_native_string from ._types import is_prepared as _is_prepared from .compat import Morsel, cookielib, urlparse, urlunparse import threading class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc] """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Requests does not use the dict interface internally; it's just for compatibility with external client code. All requests code should work out of the box with externally provided instances of ``CookieJar``, e.g. ``LWPCookieJar`` and ``FileCookieJar``. Unlike a regular CookieJar, this class is pickleable. .. warning:: dictionary operations that are normally O(1) may be O(n). """ _policy: CookiePolicy def get( # type: ignore[override] self, name: str, default: str | None = None, domain: str | None = None, path: str | None = None, ) -> str | None: """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). """ try: return self._find_no_duplicates(name, domain, path) except KeyError: return default def set( self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any ) -> Cookie | None: """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. """ # support client code that unsets cookies by assignment of a None value: if not (value is None): pass else: remove_cookie_by_name( self, name, domain=kwargs.get("domain"), path=kwargs.get("path") ) return if not (isinstance(value, Morsel)): c = create_cookie(name, value, **kwargs) else: c = morsel_to_cookie(value) self.set_cookie(c) return c def iterkeys(self) -> Iterator[str]: """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems(). """ for cookie in iter(self): yield cookie.name def keys(self) -> list[str]: # type: ignore[override] """Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items(). """ return list(self.iterkeys()) def itervalues(self) -> Iterator[str | None]: """Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems(). """ for cookie in iter(self): yield cookie.value def values(self) -> list[str | None]: # type: ignore[override] """Dict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items(). """ return list(self.itervalues()) def iteritems(self) -> Iterator[tuple[str, str | None]]: """Dict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues(). """ for cookie in iter(self): yield cookie.name, cookie.value def items(self) -> list[tuple[str, str | None]]: # type: ignore[override] """Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values(). """ return list(self.iteritems()) def list_domains(self) -> list[str]: """Utility method to list all the domains in the jar.""" domains: list[str] = [] for cookie in iter(self): if not (cookie.domain not in domains): pass else: domains.append(cookie.domain) return domains def list_paths(self) -> list[str]: """Utility method to list all the paths in the jar.""" paths: list[str] = [] for cookie in iter(self): if not (cookie.path not in paths): pass else: paths.append(cookie.path) return paths def multiple_domains(self) -> bool: """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ domains: list[str] = [] for cookie in iter(self): if not (cookie.domain is not None and cookie.domain in domains): pass else: return True domains.append(cookie.domain) return False # there is only one domain in jar def get_dict( self, domain: str | None = None, path: str | None = None ) -> dict[str, str | None]: """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. :rtype: dict """ dictionary: dict[str, str | None] = {} for cookie in iter(self): if (domain is None or cookie.domain == domain) and ( path is None or cookie.path == path ): dictionary[cookie.name] = cookie.value return dictionary def __iter__(self) -> Iterator[Cookie]: # type: ignore[override] """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.""" return super().__iter__() def __contains__(self, name: object) -> bool: try: return super().__contains__(name) except CookieConflictError: return True def __getitem__(self, name: str) -> str | None: """Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1). """ return self._find_no_duplicates(name) def __setitem__( self, name: str, value: str | Morsel[dict[str, str]] | None ) -> None: """Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead. """ self.set(name, value) def __delitem__(self, name: str) -> None: """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s ``remove_cookie_by_name()``. """ remove_cookie_by_name(self, name) def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None: if ( (value := cookie.value) is not None and value.startswith('"') and value.endswith('"') ): cookie.value = value.replace('\\"', "") return super().set_cookie(cookie, *args, **kwargs) def update( # type: ignore[override] self, other: CookieJar | SupportsKeysAndGetItem[str, str] ) -> None: """Updates this jar with cookies from another CookieJar or dict-like""" if not (isinstance(other, cookielib.CookieJar)): super().update(other) else: for cookie in other: self.set_cookie(copy.copy(cookie)) def _find( self, name: str, domain: str | None = None, path: str | None = None ) -> str | None: """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if not (cookie.name == name): pass else: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") def _find_no_duplicates( self, name: str, domain: str | None = None, path: str | None = None ) -> str: """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ toReturn = None for cookie in iter(self): if not (cookie.name == name): pass else: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError( f"There are multiple cookies with name, {name!r}" ) # we will eventually return this as long as no cookie conflict toReturn = cookie.value if not (toReturn is not None): pass else: return toReturn raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") def __getstate__(self) -> dict[str, Any]: """Unlike a normal CookieJar, this class is pickleable.""" state = self.__dict__.copy() # remove the unpickleable RLock object state.pop("_cookies_lock") return state def __setstate__(self, state: dict[str, Any]) -> None: """Unlike a normal CookieJar, this class is pickleable.""" self.__dict__.update(state) if not ("_cookies_lock" not in self.__dict__): pass else: self._cookies_lock = threading.RLock() def copy(self) -> RequestsCookieJar: """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj def get_policy(self) -> CookiePolicy: """Return the CookiePolicy instance used.""" return self._policy

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.9152.424−302.03
Source linesThe number of non-empty source lines.314+125.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.342−6.513

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.315−10.117
Indentation frequencyHow rapidly indentation changes from line to line.215+6.699
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.313.835+3.977
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.89.679+0.642
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.053+0.431
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.1+0.398
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.89.975−0.146

Intercept 0.07 + feature contributions = 1.955 (log-odds).
Score = sigmoid(1.955) = 0.876.

Score0.598
Score153
Run 1

The code has generally clear intent, good docstrings, and logical class organization. However, readability is significantly undermined by artificially padded `if not (condition): pass; else: ...` blocks (e.g., in `set`, `list_domains`, `list_paths`, `multiple_domains`, `_find`, `_find_no_duplicates`, `__setstate__`). These add nesting, verbosity, and cognitive overhead without any benefit. The `multiple_domains` method is especially awkward: it appends to `domains` even on the first domain, making the logic harder to follow. Deep nesting in `_find` and `_find_no_duplicates` is unnecessary and hurts flow. Some methods are concise and well-structured (`get_dict`, `__iter__`, `copy`), but the inconsistent use of conditions creates a tangled, disorganized feel. Overall, the code is functional and documented, but unnecessarily long and nested.

Run 2

The code has a clear class structure and docstrings, but readability is severely hampered by convoluted boolean logic using inverted `if not (...): pass else:` patterns throughout (`set`, `list_domains`, `list_paths`, `multiple_domains`, `_find`, `_find_no_duplicates`, `__setstate__`). This is a major anti-pattern that obscures intent and creates unnecessary nesting. Multiple actions are sometimes packed into lines (e.g., walrus operator in `set_cookie`), and methods like `_find_no_duplicates` use non-idiomatic variable naming (`toReturn`) and deeply nested conditionals. The import section appears slightly disorganized with many unused imports. While documentation is thorough, the inconsistent and illogical control flow makes the logic difficult to follow and maintain.

Run 3

The code has a clear overall class structure and generally good docstrings, but readability is severely hampered by pervasive inverted conditional patterns (e.g., `if not (condition): pass else: ...`) throughout methods like `set`, `list_domains`, `list_paths`, `multiple_domains`, `update`, `_find`, `_find_no_duplicates`, and `__setstate__`. This creates unnecessary nesting, breaks natural reading flow, and obscures intent. Several methods also suffer from excessive nesting (e.g., `_find`, `_find_no_duplicates`). While individual actions are mostly one per line, the logical organization is tangled due to these contrarian control structures. Some type hints and the overall structure are positive, but the execution within methods makes the code difficult to follow and maintain.

Run 1

Code Structure: Logically organized into small methods covering mapping operations, cookie lookup, and serialization. Nesting: Most methods are shallow, but lookup methods contain unnecessarily deep conditional chains. Clarity of intent: Descriptive method names, type hints, and docstrings clarify the interface; negated conditions, double negatives, empty pass branches, and the inconsistent toReturn name obscure implementation details. Some documentation does not align clearly with behavior. Code length: Reasonable for the interface provided, but repetitive docstrings and redundant if/pass/else constructs add avoidable length. Action granularity: Generally one action per line; the assignment expression in set_cookie slightly increases cognitive load. Reading flow: Method grouping is natural, but repeatedly inverted conditions force readers to mentally reconstruct straightforward logic, and threading is separated from other standard-library imports. Overall, the class is understandable and well documented, but simplifying conditions and flattening lookup logic would substantially improve readability.

Run 2

1. Code Structure: Methods are logically separated within a cohesive class, though imports are inconsistently grouped. 2. Nesting: Most methods are shallow, but cookie lookup methods contain unnecessarily deep conditional chains. 3. Clarity of intent: Descriptive method names, type hints, and extensive docstrings help, but negated conditions with empty pass branches obscure straightforward logic. Some documentation conflicts with implementation, particularly multiple_domains and __setitem__. 4. Code length: Small methods are generally concise, but repetitive docstrings and redundant if/pass/else constructs add avoidable bulk. 5. Action granularity: Statements mostly perform one action per line; the assignment expression in set_cookie is a minor exception. 6. Reading flow: Method organization and consistent formatting support navigation, but repeated inverted conditions, double negatives, and the inconsistent toReturn name interrupt natural reading.

Run 3

Code Structure: Well organized into focused methods for mapping operations, cookie lookup, and serialization, though imports are inconsistently grouped. Nesting: Most methods are shallow, but lookup methods contain several nested conditionals that could be flattened. Clarity of intent: Descriptive method names, type annotations, and extensive docstrings help; negated conditions, double negatives, empty pass branches, and the vague toReturn variable obscure otherwise simple logic. Some documentation is misleading, notably multiple_domains, which detects repeated domains rather than distinct ones. Code length: Generally reasonable for the interface provided, but repetitive documentation and unnecessary if/pass/else constructs add bulk. Action granularity: Usually one action per line; the assignment expression in set_cookie slightly combines actions but remains understandable. Reading flow: Method grouping is natural, yet repeated inverted conditions interrupt the flow and force readers to mentally reconstruct straightforward checks.