Sample

pyint-0959f447832e-I13

Lower every eligible synchronous for loop to a while loop

Matched original source

Lines98

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.9190–1; higher is more readable
Mi0.5610–1; higher is more readable
LLOC38Logical lines; fewer is more readable
DeepSeek V4 Pro170–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.5810–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 RequestHooksMixin: hooks: dict[str, list[_t.HookType]] def register_hook( self, event: str, hook: Iterable[_t.HookType] | _t.HookType ) -> None: """Properly register a hook.""" if event not in self.hooks: raise ValueError(f'Unsupported event specified, with event name "{event}"') if isinstance(hook, Callable): self.hooks[event].append(hook) elif hasattr(hook, "__iter__"): self.hooks[event].extend( h for h in hook if isinstance(h, Callable) ) # defensive runtime filter def deregister_hook(self, event: str, hook: _t.HookType) -> bool: """Deregister a previously registered hook. Returns True if the hook existed, False if not. """ try: self.hooks[event].remove(hook) return True except ValueError: return False

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.2524.999−83.325
Source linesThe number of non-empty source lines.98+39.2
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.658−6.987

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

Feature contributions

FeatureValueContribution
(log-odds)
Indentation frequencyHow rapidly indentation changes from line to line.94+2.514
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.99−2.469
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.97.875+0.958
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.99+0.599
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.1+0.398
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.058+0.379
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.86.929−0.017

Intercept 0.07 + feature contributions = 2.433 (log-odds).
Score = sigmoid(2.433) = 0.919.

Score0.561
Score38
Run 1

The code is highly readable. The structure is logical: imports are grouped by source and then classes/functions follow, with related methods cohesive within a mixin. Nesting is minimal, restricted to a single level in conditionals and a generator expression. Intent is clearly conveyed through descriptive names (register_hook, deregister_hook), type hints, and concise docstrings explaining behavior. Length is appropriate, importing only necessary utilities even if the import block is long—it is standard for library code. Each line performs one action. Reading flow is natural: imports, then class definition, with the deregister_hook's try/except clearly mapping to success/failure. Minor notes: the inline comment in the generator is helpful, and the isinstance check against Callable—though correct for runtime—can be slightly unusual since callable() exists, but not a readability flaw in this codebase.

Run 2

The code is generally well-structured and readable. The imports are explicitly organized, clearly separating standard library, third-party (urllib3), and local modules. Type annotations and the `__future__` import demonstrate modern Python practices, enhancing clarity. The class `RequestHooksMixin` is logically cohesive with concise methods. `register_hook` and `deregister_hook` are flat, with minimal nesting, and each performs a single logical action per line. Intent is clear from the method and parameter names. However, the import block is overly long, which reduces initial readability. The `isinstance(hook, Callable)` check is incorrect—`Callable` from `collections.abc` cannot be used directly as the second argument to `isinstance` without `typing` generics or `types.FunctionType`, which is a subtle bug and source of confusion. The defensive generator expression in `extend` is slightly dense but still readable. Overall, the code is maintainable but could benefit from simplifying imports and correcting the callable check.

Run 3

The code is generally readable with clear structure and intent. Imports are well-organized and logically grouped, separating third-party from internal modules. The class methods have clear purposes reflected in their names and docstrings. Nesting is minimal, with only one level in the register_hook method. However, the long list of imports adds noise and length to the file, detracting from readability. The isinstance checks with callable filtering in register_hook could be slightly clearer with a comment explaining the defensive filter, but the inline comment helps. Overall, the code is functional and maintainable, though not exemplary in conciseness.

Run 1

Code Structure: Imports are grouped by source, and hook operations are cleanly encapsulated in a focused mixin. Nesting: Methods remain shallow, with straightforward conditionals and exception handling. Clarity of intent: Descriptive method names, type annotations, and docstrings explain registration and deregistration; the runtime callable filter is explicitly documented. Code length: Method implementations are concise, but the extensive import section overwhelms this small excerpt, with many imports unused in the shown code. Action granularity: Each statement performs a single clear operation; the generator expression compactly combines filtering and iteration without excessive complexity. Reading flow: Validation precedes mutation, and deregistration follows a natural attempt-and-result sequence. Minor spacing inconsistencies and the disproportionate import block slightly reduce scanability.

Run 2

Code Structure: Imports are grouped logically, and hook management is encapsulated in a focused mixin. Nesting: Methods remain shallow, with straightforward conditionals and exception handling. Clarity of intent: Descriptive names, type annotations, and docstrings make registration and deregistration easy to understand; callable filtering is explicitly documented. Code length: Methods are concise, though the extensive import block dominates this excerpt and includes many imports unused here. Action granularity: Statements generally perform one action per line; the generator expression compactly combines iteration and filtering without becoming obscure. Reading flow: Validation precedes mutation, and deregistration follows a natural try/remove/return sequence. Minor readability costs include abbreviated aliases, runtime checks that differ from the annotated interface, and the disproportionate import preamble.

Run 3

Code Structure: Imports are grouped coherently, and hook operations are cleanly encapsulated in a small mixin. Nesting: Methods use shallow conditionals and a straightforward try/except, making control flow easy to follow. Clarity of intent: Descriptive names, type annotations, and docstrings clearly explain registration and deregistration; the runtime filtering behavior is briefly documented. Code length: Methods are concise, but the extensive import section overwhelms this excerpt, with most imports unused in the shown code. Action granularity: Each statement performs a distinct action, without compressed multi-action lines. Reading flow: Validation precedes registration naturally, and deregistration reads sequentially; however, the long import preamble delays reaching the relevant functionality, and the wrapped generator expression slightly interrupts flow.