Sample

pyint-803f7c9f1613-I01

Remove comments and docstrings

Matched original source

Lines457

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0080–1; higher is more readable
Mi0.7290–1; higher is more readable
LLOC195Logical lines; fewer is more readable
DeepSeek V4 Pro150–20; mean of three runs
GPT-6.1 Sol140–20; mean of three runs
BTTF0.4040–1; higher is more readable

Views

Source code

from __future__ import annotations import datetime import encodings.idna from collections.abc import Callable, Generator, Iterable, Iterator, Mapping from io import UnsupportedOperation from typing import ( TYPE_CHECKING, Any, Final, Literal, cast, overload, ) from urllib3.exceptions import ( DecodeError, LocationParseError, ProtocolError, ReadTimeoutError, SSLError, ) from urllib3.fields import RequestField from urllib3.filepost import encode_multipart_formdata from urllib3.util import parse_url from . import _types as _t from ._internal_utils import to_native_string, unicode_is_ascii from .auth import HTTPBasicAuth from .compat import ( JSONDecodeError, basestring, builtin_str, chardet, cookielib, urlencode, urlsplit, urlunparse, ) from .compat import json as complexjson from .cookies import ( _copy_cookie_jar, cookiejar_from_dict, get_cookie_header, ) from .exceptions import ( ChunkedEncodingError, ConnectionError, ContentDecodingError, HTTPError, InvalidJSONError, InvalidURL, MissingSchema, StreamConsumedError, ) from .exceptions import JSONDecodeError as RequestsJSONDecodeError from .exceptions import SSLError as RequestsSSLError from .hooks import default_hooks from .status_codes import codes from .structures import CaseInsensitiveDict from .utils import ( check_header_validity, get_auth_from_url, guess_filename, guess_json_utf, iter_slices, parse_header_links, requote_uri, stream_decode_response_unicode, super_len, to_key_val_list, ) class Response: _content: bytes | Literal[False] | None _content_consumed: bool _next: PreparedRequest | None status_code: int headers: CaseInsensitiveDict[str] raw: Any url: str encoding: str | None history: list[Response] reason: str cookies: RequestsCookieJar elapsed: datetime.timedelta request: PreparedRequest connection: HTTPAdapter __attrs__: list[str] = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] def __init__(self) -> None: self._content = False self._content_consumed = False self._next = None self.status_code = None self.headers = CaseInsensitiveDict() self.raw = None self.url = None self.encoding = None self.history = [] self.reason = None self.cookies = cookiejar_from_dict({}) self.elapsed = datetime.timedelta(0) self.request = None def __enter__(self) -> Self: return self def __exit__(self, *args: Any) -> None: self.close() def __getstate__(self) -> dict[str, Any]: if not self._content_consumed: self.content return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state: dict[str, Any]) -> None: for name, value in state.items(): setattr(self, name, value) setattr(self, "_content_consumed", True) setattr(self, "raw", None) def __repr__(self) -> str: return f"<Response [{self.status_code}]>" def __bool__(self) -> bool: return self.ok def __nonzero__(self) -> bool: return self.ok def __iter__(self) -> Iterator[bytes]: return self.iter_content(128) @property def ok(self) -> bool: try: self.raise_for_status() except HTTPError: return False return True @property def is_redirect(self) -> bool: return "location" in self.headers and self.status_code in REDIRECT_STATI @property def is_permanent_redirect(self) -> bool: return "location" in self.headers and self.status_code in ( codes.moved_permanently, codes.permanent_redirect, ) @property def next(self) -> PreparedRequest | None: return self._next @property def apparent_encoding(self) -> str | None: if chardet is not None: return chardet.detect(self.content)["encoding"] else: return "utf-8" @overload def iter_content( self, chunk_size: int | None = 1, decode_unicode: Literal[False] = False ) -> Iterator[bytes]: ... @overload def iter_content( self, chunk_size: int | None = 1, *, decode_unicode: Literal[True] ) -> Iterator[str | bytes]: ... def iter_content( self, chunk_size: int | None = 1, decode_unicode: bool = False ) -> Iterator[str | bytes]: def generate() -> Generator[bytes, None, None]: if hasattr(self.raw, "stream"): try: yield from self.raw.stream(chunk_size, decode_content=True) except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecodingError(e) except ReadTimeoutError as e: raise ConnectionError(e) except SSLError as e: raise RequestsSSLError(e) else: while True: chunk = self.raw.read(chunk_size) if not chunk: break yield chunk self._content_consumed = True if self._content_consumed and isinstance(self._content, bool): raise StreamConsumedError() elif chunk_size is not None and not isinstance( chunk_size, int ): raise TypeError( f"chunk_size must be an int, it is instead a {type(chunk_size)}." ) if self._content_consumed: content = cast(bytes, self._content) chunks = iter_slices(content, chunk_size) else: chunks = generate() if decode_unicode: chunks = stream_decode_response_unicode(chunks, self) return chunks @overload def iter_lines( self, chunk_size: int = ITER_CHUNK_SIZE, decode_unicode: Literal[False] = False, delimiter: bytes | None = None, ) -> Iterator[bytes]: ... @overload def iter_lines( self, chunk_size: int = ITER_CHUNK_SIZE, *, decode_unicode: Literal[True], delimiter: str | bytes | None = None, ) -> Iterator[str | bytes]: ... def iter_lines( self, chunk_size: int = ITER_CHUNK_SIZE, decode_unicode: bool = False, delimiter: str | bytes | None = None, ) -> Iterator[str | bytes]: pending: str | bytes | None = None for chunk in self.iter_content( chunk_size=chunk_size, decode_unicode=decode_unicode ): if pending is not None: chunk = cast("str | bytes", pending + chunk) if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]: pending = lines.pop() else: pending = None yield from lines if pending is not None: yield pending @property def content(self) -> bytes: if self._content is False: if self._content_consumed: raise RuntimeError("The content for this response was already consumed") if self.status_code == 0 or self.raw is None: self._content = None else: self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b"" self._content_consumed = True return self._content @property def text(self) -> str: content = None encoding = self.encoding if not self.content: return "" if self.encoding is None: encoding = self.apparent_encoding try: content = str(self.content, encoding or "utf-8", errors="replace") except (LookupError, TypeError): content = str(self.content, errors="replace") return content def json(self, **kwargs: Any) -> Any: if not self.encoding and self.content and len(self.content) > 3: encoding = guess_json_utf(self.content) if encoding is not None: try: return complexjson.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: pass except JSONDecodeError as e: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) try: return complexjson.loads(self.text, **kwargs) except JSONDecodeError as e: raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) @property def links(self) -> dict[str, dict[str, str]]: header = self.headers.get("link") resolved_links: dict[str, dict[str, str]] = {} if header: links = parse_header_links(header) for link in links: key = link.get("rel") or link.get("url") if key is not None: resolved_links[key] = link return resolved_links def raise_for_status(self) -> None: http_error_msg = "" if isinstance(self.reason, bytes): try: reason = self.reason.decode("utf-8") except UnicodeDecodeError: reason = self.reason.decode("iso-8859-1") else: reason = self.reason if 400 <= self.status_code < 500: http_error_msg = ( f"{self.status_code} Client Error: {reason} for url: {self.url}" ) elif 500 <= self.status_code < 600: http_error_msg = ( f"{self.status_code} Server Error: {reason} for url: {self.url}" ) if http_error_msg: raise HTTPError(http_error_msg, response=self) def close(self) -> None: if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, "release_conn", None) if release_conn is not None: release_conn()

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.13661.759−450.838
Source linesThe number of non-empty source lines.457+182.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.182−6.273

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.458−15.18
Indentation frequencyHow rapidly indentation changes from line to line.457+15.07
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.457−10.066
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.456.955+5.978
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.0−0.804
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.078+0.185
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.87.961−0.06

Intercept 0.07 + feature contributions = -4.808 (log-odds).
Score = sigmoid(-4.808) = 0.008.

Score0.729
Score195
Run 1

The code is generally well-structured and readable. It follows a logical organization with clear import grouping, typed annotations, and consistent formatting. Methods are named clearly and serve distinct purposes. Nesting is moderate; methods like iter_content and raise_for_status use conditional blocks but remain comprehensible. The use of type hints and docstrings (though many are placeholder) supports clarity. However, the code is somewhat verbose in places, particularly in iter_content where overloads and nested conditionals add complexity. Action granularity is mostly one action per line, improving readability, though some lines are dense (e.g., chunk = cast("str | bytes", pending + chunk)). The reading flow is natural, with properties and methods ordered predictably. The primary detractors are the presence of multiple empty comments as placeholders and minor redundancy in type checking, but overall the code is clear, maintainable, and professional.

Run 2

The code demonstrates good readability with clear class structure, logical method organization, and well-documented sections. Methods are appropriately short and focused on single responsibilities. Type hints and overloads enhance clarity. However, there are minor issues: some deeply nested logic in methods like json() and raise_for_status(), multiple inline comments that could be consolidated, and a few methods that could be broken down further. The blank lines and comment blocks in __init__ improve readability but add unnecessary length. Overall, the code is well-structured and maintainable, following consistent patterns throughout.

Run 3

This is a well-structured class with clear attribute definitions and logical method organization. However, readability is hampered by inconsistent indentation, numerous commented-out code blocks, and excessive whitespace. The nested generator and exception handling in `iter_content` add complexity. Type hints are helpful, but overloads and imports add bulk. Comments often explain 'what' rather than 'why', and many blank or placeholder comments create noise. The code lacks a consistent documentation style and contains redundant methods like `__nonzero__`. Overall, the intent is clear to an experienced developer but requires patience to parse due to formatting inconsistencies and verbose annotations.

Run 1

Code Structure: Methods and properties logically group response behavior, though the extensive import block includes unrelated dependencies. Nesting: Mostly shallow, but streaming and JSON decoding introduce moderately nested exception handling. Clarity of intent: Descriptive names and type annotations communicate purpose; missing documentation obscures content-consumption state, encoding fallbacks, and partial-line handling. Some annotations conflict with assigned or returned None values, and several referenced names are not defined in the snippet. Code length: Individual methods are generally focused, but excessive blank lines, imports, and repeated overload signatures make the class unnecessarily lengthy to scan. Action granularity: Statements predominantly perform one action per line, with compact expressions remaining manageable. Reading flow: Method ordering is natural, progressing from initialization and lifecycle operations to content access and error handling, but inconsistent whitespace and unexplained edge cases interrupt comprehension.

Run 2

Code Structure: Responsibilities are logically separated into focused methods and properties, though the large import block includes many names unused in this excerpt. Nesting: Mostly shallow, with moderate nesting in streaming, JSON decoding, and link parsing. Clarity of intent: Descriptive method names and type annotations help, but missing documentation, unexplained content-state sentinels, annotation/value inconsistencies, and externally defined names obscure details. Code length: Excessive blank lines and repeated overload signatures make the class visually longer than necessary. Action granularity: Statements generally perform one action per line, and exception handling is explicit. Reading flow: Method organization is coherent, but whitespace clutter, subtle state changes during property access, and complex conditions interrupt otherwise natural reading.

Run 3

Code Structure: The Response class is logically divided into focused methods and properties, though numerous unrelated imports add clutter. Nesting: Most methods are shallow, but streaming and JSON decoding contain moderately nested branches and exception handling. Clarity of intent: Descriptive method names and type annotations help, but missing documentation, unexplained content-state sentinels, unresolved names in the excerpt, and annotations inconsistent with assigned values reduce clarity. Code length: Excessive blank lines, unused imports, and repeated overload signatures make the excerpt longer to scan than necessary. Action granularity: Statements generally perform one action per line, with readable expressions and well-separated exception handlers. Reading flow: The progression from initialization to response inspection, content processing, and cleanup is natural, but whitespace gaps and subtle state transitions interrupt comprehension.