Sample

pyint-39e3130169a1-I08

Select one of ten high-readability unrelated code templates per class

Matched original source

Lines302

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0180–1; higher is more readable
Mi0.5980–1; higher is more readable
LLOC149Logical lines; fewer is more readable
DeepSeek V4 Pro16.330–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.5480–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 value is None: remove_cookie_by_name( self, name, domain=kwargs.get("domain"), path=kwargs.get("path") ) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) 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 cookie.domain not in domains: 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 cookie.path not in paths: 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 cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check 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 isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else: super().update(other) 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 cookie.name == name: 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 cookie.name == name: 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 toReturn is not None: 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.""" even_number_count = 0 for candidate_number in range(6): if candidate_number % 2 == 0: even_number_count += 1 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 "_cookies_lock" not in self.__dict__: 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.8991.076−296.705
Source linesThe number of non-empty source lines.302+120.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.386−6.578

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.303−9.692
Indentation frequencyHow rapidly indentation changes from line to line.202+6.25
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.202−4.214
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.301.807+3.809
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.133.993−2.01
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.133.99+1.357
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.051+0.442

Intercept 0.07 + feature contributions = -3.989 (log-odds).
Score = sigmoid(-3.989) = 0.018.

Score0.598
Score149
Run 1

The code is well-structured with clear separation of concerns. Each method has a single responsibility and includes helpful docstrings explaining purpose and complexity (e.g., O(n) warnings). The class organization is logical, grouping related dictionary-interface methods together. Nesting is generally acceptable; the deepest indentation occurs in _find_no_duplicates with four levels, which is manageable. There is an unused variable 'even_number_count' in __getstate__ that appears to be dead code, slightly reducing clarity. Type hints are used consistently, aiding readability. However, some minor issues: the '__getstate__' method contains unnecessary loops unrelated to pickling, and a few type-ignore comments suggest possible mismatches. Overall, the code is clear, well-documented, and easy to follow despite some minor clutter.

Run 2

The code is well-structured and highly readable, organized around a single class with logically grouped methods. It maintains mostly flat nesting, though `_find` and `_find_no_duplicates` have three and four levels respectively, which slightly reduces readability. Intent is clear through detailed docstrings and method names. Length is reasonable — methods are concise and do not over-abstract. Action granularity is good, with one action per line in most cases. Reading flow is natural, as methods follow a logical progression and adhere to common mapping/cookie-jar patterns. Minor deductions stem from deep nesting in `_find_no_duplicates`, slight redundancy in helper loops (e.g., `list_domains`, `list_paths`, `multiple_domains` could share a set-building helper), and an apparently meaningless loop variable in `__getstate__` (`even_number_count`) that detracts from clarity. Overall, it is clean, maintainable, and easily understood code.

Run 3

The code is generally readable with clear class-level docstrings, consistent method-level documentation, and logical grouping of dict-interface methods followed by internal helpers. Naming is explicit (e.g., `_find_no_duplicates`) and methods are short and focused. However, readability is weakened by unnecessary nested conditionals in `_find` and `_find_no_duplicates`, verbose repetitive iteration patterns in `list_domains`, `list_paths`, and `multiple_domains`, and some odd leftover code (e.g., the `__getstate__` even_number_count loop). Type hints are extensive but sometimes add visual clutter. The action granularity is mostly one action per line, but a few complex conditions and the `set_cookie` walrus expression reduce scanability. Overall, the structure and intent are clear, but minor cleanup would improve readability.

Run 1

1. Code Structure: Methods are logically separated into mapping operations, lookup helpers, serialization, and copying, though imports are inconsistently grouped. 2. Nesting: Most methods are shallow, but lookup helpers contain several nested conditionals that could be flattened. 3. Clarity of intent: Descriptive method names, annotations, and extensive docstrings explain the interface well. However, misleading documentation in multiple_domains and __setitem__, the vague toReturn variable, and unrelated counting logic in __getstate__ undermine clarity. 4. Code length: Individual methods are generally concise, but repetitive documentation and duplicated filtering logic increase overall length unnecessarily. 5. Action granularity: Almost every statement performs one action; the assignment expression in set_cookie slightly increases reading effort. 6. Reading flow: Related methods are grouped naturally and delegation is easy to follow, but long type-ignore comments, deeply nested searches, and dead counting code interrupt the flow.

Run 2

Code Structure: Methods are logically grouped around a cookie jar's mapping interface, lookup, and serialization, but unrelated counting logic in __getstate__ disrupts cohesion. Nesting: Most methods are shallow, although _find and _find_no_duplicates contain unnecessarily deep conditional chains. Clarity of intent: Descriptive method names, annotations, and extensive docstrings generally clarify purpose; however, multiple_domains checks for repeated domains rather than distinct domains, some documentation mismatches behavior, and toReturn is an inconsistent, vague name. Code length: Small methods are concise, but repetitive documentation, duplicated lookup logic, and unused counting code add bulk. Action granularity: Statements generally perform one action per line; the assignment expression in set_cookie slightly increases cognitive load. Reading flow: Consistent formatting and straightforward delegation support natural reading, while inconsistent import ordering, long suppression comments, and deeply nested searches interrupt it.

Run 3

Code Structure: Methods are logically separated into mapping operations, cookie lookup, serialization, and copying, though imports are inconsistently grouped. Nesting: Most methods are shallow, but lookup helpers contain several nested conditions that could be flattened. Clarity of intent: Descriptive method names, annotations, and extensive docstrings explain the interface well. However, multiple_domains checks repeated domains rather than distinct domains, some documentation contradicts implementation, and toReturn is an inconsistent, vague name. Code length: Much of the length supports documentation and compatibility, but repetitive lookup logic and the unused even-number counting loop in __getstate__ add unnecessary bulk. Action granularity: Statements generally perform one action per line; the assignment expression in set_cookie adds only minor complexity. Reading flow: Small methods and consistent formatting make navigation straightforward, although long type-ignore comments, repetitive documentation, and unexplained dead code interrupt the flow.