Sample

pyint-25f1fdce3145-I05

Rewrite eligible decimal integer literals in hexadecimal notation

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 Pro17.330–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 with clear imports, type hints, and docstrings. The class RequestHooksMixin has two focused methods, each with a single responsibility. Nesting is minimal—only one level deep in register_hook's conditional logic. The intent is clear: registering and deregistering hooks with validation. Action granularity is mostly one action per line, though the list comprehension/filter in register_hook packs multiple operations (iteration, filtering, extending) into one line, slightly reducing clarity. The reading flow is natural: imports first, then class definition, then methods with clear names. Type hints improve readability. Minor deductions: the one-line comprehension could be more explicit, and the conditional logic in register_hook could be slightly flatter, but overall the code is highly readable and maintainable.

Run 3

The code is generally well-structured with clear imports and a cohesive class definition. The RequestHooksMixin class has a single responsibility, and methods are short with clear intent. However, readability is slightly reduced by the lengthy import block and a few dense lines, such as the extended generator with an inline comment. Type hints improve clarity, and error handling is straightforward. Overall, the code is readable but not maximally concise or flat.

Run 1

Code Structure: Imports are grouped by source, and hook operations are cleanly encapsulated in a focused mixin. Nesting: Methods use shallow conditionals and a simple try/except, making control flow easy to follow. Clarity of intent: Descriptive method names, type annotations, and docstrings clearly communicate registration and removal behavior, though silently filtering non-callable hooks is less obvious. Code length: Method implementations are concise, but the extensive import block overwhelms this small excerpt and includes many imports not used here. Action granularity: Statements generally perform one action per line; the filtering generator remains understandable. Reading flow: Registration followed by deregistration is natural, although the long import preamble and slightly awkward wrapping of extend interrupt the otherwise straightforward presentation.

Run 2

Code Structure: Imports are grouped logically, and hook management is cleanly encapsulated in a focused mixin. Nesting: Both methods remain shallow, using straightforward conditionals and exception handling. Clarity of intent: Descriptive method names, type annotations, docstrings, and explicit error messages make behavior clear; the iterable check and runtime filtering require slightly more interpretation. Code length: Method implementations are concise, but the extensive import section is disproportionate to the displayed functionality and adds reading overhead. Action granularity: Statements generally perform one action per line, with the generator expression providing a compact, understandable filter. Reading flow: Registration followed by deregistration creates a natural progression, although the large import preamble delays reaching the relevant logic.

Run 3

Code Structure: Imports are grouped sensibly, and hook management is cleanly encapsulated in a focused mixin. Nesting: Methods remain shallow, with straightforward conditionals and exception handling. Clarity of intent: Descriptive method names, type annotations, docstrings, and the defensive-filter comment make behavior understandable, although checking __iter__ rather than Iterable is slightly less direct. Code length: The methods are concise, but the extensive import section dominates this excerpt and includes many names unused within it. Action granularity: Each statement generally performs one clear action; the generator expression compactly expresses filtering. Reading flow: Registration validation precedes mutation naturally, and deregistration clearly communicates success or failure. Overall, readability is strong, with minor distractions from import volume and compact runtime filtering.