Sample

pyint-cf5b9b7e54f6-I01

Remove comments and docstrings

Matched original source

Lines395

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0180–1; higher is more readable
Mi0.7290–1; higher is more readable
LLOC182Logical lines; fewer is more readable
DeepSeek V4 Pro14.670–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.3840–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 PreparedRequest(RequestEncodingMixin, RequestHooksMixin): method: str | None url: str | None headers: CaseInsensitiveDict[str | bytes] _cookies: RequestsCookieJar | CookieJar | None body: _t.BodyType hooks: dict[str, list[_t.HookType]] _body_position: int | object | None def __init__(self) -> None: self.method = None self.url = None self.headers = None self._cookies = None self.body = None self.hooks = default_hooks() self._body_position = None def prepare( self, method: str | None = None, url: _t.UriType | None = None, headers: Mapping[str, str | bytes] | None = None, files: _t.FilesType = None, data: _t.DataType = None, params: _t.ParamsType = None, auth: _t.AuthType = None, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None = None, hooks: _t.HooksInputType | None = None, json: _t.JsonType = None, ) -> None: url = cast("_t.UriType", url) self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) self.prepare_auth(auth, url) self.prepare_hooks(hooks) def __repr__(self) -> str: return f"<PreparedRequest [{self.method}]>" def copy(self) -> PreparedRequest: p = PreparedRequest() p.method = self.method p.url = self.url p.headers = self.headers.copy() if self.headers is not None else None p._cookies = _copy_cookie_jar(self._cookies) p.body = self.body p.hooks = self.hooks p._body_position = self._body_position return p def prepare_method(self, method: str | None) -> None: self.method = method if self.method is not None: self.method = to_native_string(self.method.upper()) @staticmethod def _get_idna_encoded_host(host: str) -> str: import idna try: host = idna.encode(host, uts46=True).decode("utf-8") except idna.IDNAError: raise UnicodeError return host def prepare_url( self, url: _t.UriType, params: _t.ParamsType, ) -> None: if isinstance(url, bytes): url = url.decode("utf8") else: url = str(url) url = url.lstrip() if ":" in url and not url.lower().startswith("http"): self.url = url return try: scheme, auth, host, port, path, query, fragment = parse_url(url) except LocationParseError as e: raise InvalidURL(*e.args) if not scheme: raise MissingSchema( f"Invalid URL {url!r}: No scheme supplied. " f"Perhaps you meant https://{url}?" ) if not host: raise InvalidURL(f"Invalid URL {url!r}: No host supplied") if not unicode_is_ascii(host): try: host = self._get_idna_encoded_host(host) except UnicodeError: raise InvalidURL("URL has an invalid label.") elif host.startswith(("*", ".")): raise InvalidURL("URL has an invalid label.") netloc = auth or "" if netloc: netloc += "@" netloc += host if port: netloc += f":{port}" if not path: path = "/" if isinstance(params, (str, bytes)): params = to_native_string(params) if params is not None: enc_params = self._encode_params(params) else: enc_params = "" if enc_params: if query: query = f"{query}&{enc_params}" else: query = enc_params url = requote_uri(urlunparse((scheme, netloc, path, "", query, fragment))) self.url = url def prepare_headers(self, headers: Mapping[str, str | bytes] | None) -> None: self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): check_header_validity(header) name, value = header self.headers[to_native_string(name)] = value def prepare_body( self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None ) -> None: body = None content_type = None if not data and json is not None: content_type = "application/json" try: body = complexjson.dumps(json, allow_nan=False) except ValueError as ve: raise InvalidJSONError(ve, request=self) if not isinstance(body, bytes): body = body.encode("utf-8") is_iterable = isinstance(data, Iterable) or hasattr(data, "__iter__") if is_iterable and not isinstance(data, (str, bytes, list, tuple, Mapping)): try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None body = data if getattr(body, "tell", None) is not None: try: self._body_position = body.tell() except OSError: self._body_position = object() if files: raise NotImplementedError( "Streamed bodies and files are mutually exclusive." ) if length: self.headers["Content-Length"] = builtin_str(length) else: self.headers["Transfer-Encoding"] = "chunked" else: raw_data = cast("_t.RawDataType | None", data) if files: (body, content_type) = self._encode_files(files, raw_data) else: if raw_data: body = self._encode_params(raw_data) if isinstance(data, basestring) or _t.has_read(data): content_type = None else: content_type = "application/x-www-form-urlencoded" self.prepare_content_length(body) if content_type and ("content-type" not in self.headers): self.headers["Content-Type"] = content_type self.body = body def prepare_content_length(self, body: _t.BodyType) -> None: if body is not None: length = super_len(body) if length: self.headers["Content-Length"] = builtin_str(length) elif ( self.method not in ("GET", "HEAD") and self.headers.get("Content-Length") is None ): self.headers["Content-Length"] = "0" def prepare_auth( self, auth: _t.AuthType, url: _t.UriType = "", ) -> None: if auth is None: url_auth = get_auth_from_url(cast(str, self.url)) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: auth_handler = HTTPBasicAuth(*auth) else: auth_handler = cast("Callable[..., PreparedRequest]", auth) r = auth_handler(self) self.__dict__.update(r.__dict__) self.prepare_content_length(self.body) def prepare_cookies( self, cookies: RequestsCookieJar | CookieJar | dict[str, str] | None ) -> None: if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookies_jar = cast("CookieJar", self._cookies) cookie_header = get_cookie_header(cookies_jar, self) if cookie_header is not None: self.headers["Cookie"] = cookie_header def prepare_hooks(self, hooks: _t.HooksInputType | None) -> None: hooks = hooks or {} for event in hooks: self.register_hook(event, hooks[event])

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.12824−423.192
Source linesThe number of non-empty source lines.395+158
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.225−6.337

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.396−12.985
Indentation frequencyHow rapidly indentation changes from line to line.395+12.925
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.394−8.62
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.394.965+5.111
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.077+0.189
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.83.96+0.109

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

Score0.729
Score182
Run 1

The code is moderately readable. It benefits from clear class structure, good type annotations, and logical method separation. Each preparation step (method, URL, headers, body, auth, cookies, hooks) is isolated in its own method, which aids comprehension. The imports are well-organized and comments occasionally clarify intent, such as why IDNA encoding is used. However, readability is reduced by excessive vertical whitespace and empty comments (lines with only '#' and no text), which break reading flow and add noise. Several methods, especially prepare_url and prepare_body, are long and contain multiple conditional branches, increasing cognitive load. Action granularity is generally one action per line, but some lines combine multiple operations or are densely packed. The nesting depth is acceptable, though prepare_body has several nested conditionals that could be flattened or extracted. Overall, the structure is sound but would benefit from removing empty comments, reducing method length, and extracting some logic for clarity.

Run 2

The code demonstrates solid structure with clear separation of methods and logical organization, but readability is hampered by several factors. The abundance of blank comment lines with '#' suggests removed documentation, leaving many sections unexplained. Deep nesting occurs in prepare_body and prepare_url methods, making flow harder to follow. While type hints are comprehensive and helpful, they add visual noise in some method signatures. The import section is overly long but logically grouped. Many methods have good single-action-per-line patterns, but some sections pack multiple operations. The reading flow is disrupted by excessive empty comments and inconsistent spacing. Variables have descriptive names, and error handling is clear. Overall, it's maintainable code that would benefit significantly from restored docstrings and some refactoring to reduce nesting.

Run 3

The code is generally well-structured and readable, with clear intent and good use of type hints. It follows a logical organization with separate methods for preparing different parts of an HTTP request, making it easy to follow the flow. The nesting is mostly flat, with only a few conditional blocks that are appropriately scoped. Action granularity is good—most lines perform a single, clear operation. However, there are some readability downsides: the code is quite long with many methods spanning 20-40 lines each, which can feel dense. There are also several commented-out sections and explanatory comments that, while helpful, add visual noise. Some method signatures are large with many optional parameters, making them slightly harder to parse at a glance. The use of casts and type annotations throughout helps clarify intent but also adds verbosity. Several nested if/else blocks in `prepare_body` and `prepare_url` create moderate cognitive load. Overall, the code would be understandable to experienced Python developers but might overwhelm junior developers or those unfamiliar with the requests library internals.

Run 1

Code Structure: Well organized into focused preparation methods, with a clear coordinating prepare method. Nesting: Generally moderate, but prepare_body has several nested branches and exception handlers that increase cognitive load. Clarity of intent: Descriptive method names and type annotations communicate purpose, though missing documentation leaves subtle streaming, authentication, and URL-handling behavior unexplained. Code length: Mostly justified by functionality, but excessive blank lines, broad imports, and some redundant branching reduce concision. Action granularity: Consistently uses one main action per line, making operations easy to follow. Reading flow: The preparation sequence is natural and helper methods are sensibly grouped, but whitespace clutter interrupts scanning. Referenced types and mixins not defined in the snippet also limit standalone comprehension.

Run 2

Code Structure: Well separated into focused preparation methods, with a clear orchestration method; the large import block and dependencies absent from the excerpt add overhead. Nesting: Mostly shallow, though prepare_body has several nested conditionals and exception handlers. Clarity of intent: Descriptive method names and type annotations communicate purpose, but missing documentation leaves streaming behavior, authentication updates, and special cases less obvious. Code length: Generally justified by functionality, but excessive blank lines and whitespace unnecessarily stretch the code. Action granularity: Statements consistently perform one action per line, making operations easy to follow. Reading flow: The preparation sequence is natural and related operations are grouped, although whitespace noise and the branching in prepare_body interrupt scanning.

Run 3

Code Structure: Well-separated preparation methods provide logical organization, with prepare() clearly coordinating the workflow. Nesting: Mostly shallow, although prepare_body() contains several nested branches and exception handlers that require extra attention. Clarity of intent: Descriptive method names and type annotations explain most operations, but missing documentation leaves subtle streaming, authentication, and encoding behavior less clear; external mixins and types also limit standalone comprehension. Code length: Generally justified by functionality, but excessive blank lines, a large import section, and the lengthy prepare_body() reduce concision. Action granularity: Statements generally perform one action per line, making individual operations easy to follow. Reading flow: The preparation sequence is natural and methods are consistently organized, but whitespace noise, scattered casts, and complex body-handling branches interrupt the flow.