Sample

pyint-39b834647959-I13

Lower every eligible synchronous for loop to a while loop

Matched original source

Lines167

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.8980–1; higher is more readable
Mi0.5610–1; higher is more readable
LLOC64Logical lines; fewer is more readable
DeepSeek V4 Pro13.330–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.3740–1; higher is more readable

Views

Source code

from __future__ import annotations import datetime import encodings.idna # noqa: F401 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 Request(RequestHooksMixin): """A user-created :class:`Request <Request>` object. Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server. :param method: HTTP method to use. :param url: URL to send. :param headers: dictionary of headers to send. :param files: dictionary of {filename: fileobject} files to multipart upload. :param data: the body to attach to the request. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param json: json for the body to attach to the request (if files or data is not specified). :param params: URL parameters to append to the URL. If a dictionary or list of tuples ``[(key, value)]`` is provided, form-encoding will take place. :param auth: Auth handler or (user, pass) tuple. :param cookies: dictionary or CookieJar of cookies to attach to this request. :param hooks: dictionary of callback hooks, for internal usage. Usage:: >>> import requests >>> req = requests.Request('GET', 'https://httpbin.org/get') >>> req.prepare() <PreparedRequest [GET]> """ hooks: dict[str, list[_t.HookType]] method: str | None url: _t.UriType | None headers: Mapping[str, str | bytes] files: _t.FilesType data: _t.DataType json: _t.JsonType params: _t.ParamsType auth: _t.AuthType cookies: RequestsCookieJar | CookieJar | dict[str, str] | None def __init__( self, method: str | None = None, url: _t.UriType | None = None, headers: _t.HeadersType = 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: # Default empty dicts for dict params. data = [] if data is None else data files = [] if files is None else files headers = {} if headers is None else headers params = {} if params is None else params hooks = {} if hooks is None else hooks self.hooks = default_hooks() loopIterator = __import__("builtins").iter(list(hooks.items())) while True: try: k, v = __import__("builtins").next(loopIterator) except __import__("builtins").StopIteration: break self.register_hook(event=k, hook=v) self.method = method self.url = url self.headers = headers self.files = files self.data = data self.json = json self.params = params self.auth = auth self.cookies = cookies def __repr__(self) -> str: return f"<Request [{self.method}]>" def prepare(self) -> PreparedRequest: """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.""" p = PreparedRequest() p.prepare( method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, json=self.json, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks, ) return p

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.4716.144−155.633
Source linesThe number of non-empty source lines.167+66.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.609−6.914

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.168−4.912
Indentation frequencyHow rapidly indentation changes from line to line.140+4.105
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.166.922+1.923
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.101.929+0.84
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.101.976−0.654
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.055+0.405
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.1+0.398

Intercept 0.07 + feature contributions = 2.176 (log-odds).
Score = sigmoid(2.176) = 0.898.

Score0.561
Score64
Run 1

The code has good structure overall, with clear type annotations, a logical organization, and readable docstrings. However, one section significantly hurts readability: the hook iteration loop in `__init__` uses dynamic `__import__('builtins')` calls with an explicit iterator, which is unnecessarily convoluted and breaks from Pythonic norms. This creates higher nesting and obscures intent compared to a simple `for k, v in hooks.items()` loop. The rest of the constructor is flat and clear. Imports are extensive but grouped, preserving readability. The class attributes are well-typed, and methods are concise. The score is lowered primarily due to that one anti-pattern, which impacts clarity of intent and reading flow.

Run 2

This code demonstrates mostly straightforward, well-structured code with clear type hints, comprehensive docstrings, and logical organization. Import statements are properly grouped and named, the class structure is clean, and most methods are readable. However, several issues reduce readability: the `__init__` method's hook registration loop uses multiple `__import__('builtins')` calls with a manual while/except iteration pattern instead of a simple `for k, v in hooks.items():` loop, which is unnecessarily complex and obscure. The type annotations use generic `dict[str, list[_t.HookType]]` etc., but some parameters like `headers: _t.HeadersType = None` accept None without Optional markers. The overall code is maintainable but the hook loop is a significant readability violation—it breaks 'one action per line' clarity and makes intent ambiguous where idiomatic Python would be clearer. The score reflects solid structure with notable localized complexity.

Run 3

The code has good structure with clear type hints, organized imports, and a well-documented class docstring. The `__init__` method follows a logical pattern with defaults and straightforward assignments, and `prepare()` is concise. However, the hook iteration block is problematic - it uses dynamic `__import__('builtins')` calls with a manual while/try/except pattern instead of a simple `for k, v in hooks.items()` loop. This creates unnecessary nesting and obscures intent for no benefit. The import section is excessively long, though it appears organized. The class attributes and method signatures are well-typed, which aids clarity. Overall, the code is readable in most parts but the contrived hook iteration logic significantly damages the reading flow and clarity of intent. A straightforward `for` loop would improve readability substantially, raising the score to 16-17. The current implementation feels obfuscated rather than concise.

Run 1

Code Structure: The class is logically organized into documented attributes, initialization, representation, and preparation, although numerous imports distract from the small implementation. Nesting: Most code is flat; the hook-registration loop adds avoidable while/try/except nesting. Clarity of intent: Descriptive names, type annotations, and detailed documentation make the request object's purpose clear. However, dynamic builtins imports and manual iterator handling obscure a simple iteration over hooks. Code length: Initialization and preparation are appropriately explicit, but the hook loop is unnecessarily verbose and could be a straightforward for loop. Action granularity: Statements generally perform one action per line, making assignments and argument mapping easy to follow. Reading flow: Methods follow a natural lifecycle, but the unconventional loop interrupts otherwise idiomatic Python. Referenced classes not defined or imported in the excerpt also require external context.

Run 2

Code Structure: The class is logically organized into documentation, type declarations, initialization, representation, and preparation, though extensive imports distract from the small class. Nesting: Most code is flat, but hook registration adds unnecessary while/try/except nesting. Clarity of intent: Descriptive attributes, type hints, and documentation clearly communicate request construction; dynamic builtins imports obscure an otherwise simple iteration. Code length: The documentation is useful, but the import block and manually implemented iterator loop make the snippet longer than necessary. Action granularity: Statements generally perform one action per line, with cleanly separated attribute assignments and arguments. Reading flow: Initialization followed by representation and preparation feels natural, but the unconventional hook loop interrupts the flow and would be clearer as a standard for loop.

Run 3

Code Structure: The class is logically organized into documentation, attribute declarations, initialization, representation, and preparation, although numerous unused imports clutter the snippet. Nesting: Most code is flat; hook registration introduces unnecessary while/try/except nesting. Clarity of intent: Descriptive names, type annotations, and comprehensive documentation make the request object's purpose clear, but dynamic builtins imports obscure a simple iteration. Code length: Most initialization is straightforward, though the import list, extensive documentation, and expanded iterator loop add substantial length. Action granularity: Statements generally perform one action per line, with clearly separated assignments and arguments. Reading flow: Initialization and preparation follow a natural sequence, but the unusual loopIterator naming and repeated __import__ calls interrupt otherwise idiomatic Python. A direct for loop over hooks.items() would improve readability considerably.