Sample

pyint-03e50fd988ae-I12

Inline all eligible single-use intermediate local variables

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 Pro16.670–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 well-structured with clear imports and logical class organization. Nesting is minimal, action granularity is good, and reading flow is natural. The hooks mixin methods are concise and focused. Minor deductions: the defensive runtime filter comment interrupts readability slightly, and some imports are unused or redundant (e.g., typing imports, 'hooks' type annotation could be clearer). The 'RequestHooksMixin' class lacks a clear docstring explaining its purpose, and the type annotation for 'hooks' dict could be more descriptive. Overall, very readable.

Run 3

The code is generally readable and follows common Python patterns. The imports are logically grouped and alphabetically sorted, which aids navigation. The RequestHooksMixin class has a clear purpose and the methods are concise with appropriate type hints and docstrings. However, readability is reduced by the large number of imports, which can overwhelm a reader at first glance. The register_hook method uses a generator expression with a defensive runtime filter, which is slightly dense but still understandable. The use of `hasattr(hook, "__iter__")` is acceptable but less explicit than `isinstance(hook, Iterable)`. The `deregister_hook` method is flat and straightforward. Overall, the code is maintainable but not exceptional in terms of reading flow, scoring 14 out of 20 due to the import volume and minor abstraction choices.

Run 1

Code Structure: Imports are grouped coherently, and hook registration and removal are separated into focused methods. Nesting: Shallow conditionals and a simple try/except keep complexity low. Clarity of intent: Descriptive names, type annotations, docstrings, and the defensive-filter comment clearly communicate behavior, although silently ignoring non-callable iterable items is slightly surprising. Code length: The methods are concise, but the extensive import section dominates this small excerpt and includes many imports not used here. Action granularity: Statements generally perform one action each; the generator expression remains straightforward. Reading flow: Registration proceeds naturally from event validation to adding hooks, and deregistration clearly handles success and failure. Import volume and minor formatting inconsistencies slightly interrupt an otherwise clean flow.

Run 2

Code Structure: Imports are grouped sensibly, and hook management is encapsulated in a focused mixin, although many imports are unused in this excerpt. Nesting: Methods remain shallow, with straightforward conditionals and a simple try/except. Clarity of intent: Descriptive method names, type annotations, docstrings, and a defensive-filter comment make behavior easy to understand; hasattr-based iterable checking is slightly less explicit. Code length: The methods are concise, but the extensive import section dominates this small excerpt. Action granularity: Statements generally perform one action per line, and the generator expression clearly handles filtering. Reading flow: Registration and deregistration appear in a natural order, with early validation and clear return paths; the lengthy imports delay reaching the relevant logic.

Run 3

Code Structure: Imports are grouped coherently, and hook management is encapsulated in a small mixin with focused methods, although the extensive imports distract from the short implementation. Nesting: Control flow is shallow, with simple conditionals and a straightforward try/except. Clarity of intent: Descriptive method names, type annotations, docstrings, and the defensive-filter comment explain behavior well; the iterable check and silent rejection of non-callable entries require some interpretation. Code length: Methods are concise, but the import-heavy excerpt adds substantial reading overhead. Action granularity: Each statement performs a distinct action, with no compressed multi-statement lines. Reading flow: Registration followed by deregistration is natural, and spacing is generally clear, though the wrapped generator expression and trailing comment slightly interrupt scanning.