Sample

pyint-a733b3338019-I11

Split eligible integer literals into pairs of short-named intermediate variables

Matched original source

Lines218

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.2050–1; higher is more readable
Mi0.5610–1; higher is more readable
LLOC100Logical lines; fewer is more readable
DeepSeek V4 Pro14.330–20; mean of three runs
GPT-6.1 Sol14.670–20; mean of three runs
BTTF0.2790–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 RequestEncodingMixin: url: str | None @property def path_url(self) -> str: """Build the path URL to use.""" url: list[str] = [] p = urlsplit(cast(str, self.url)) path = p.path if not path: path = "/" url.append(path) query = p.query if query: url.append("?") url.append(query) return "".join(url) @overload @staticmethod def _encode_params(data: str) -> str: ... @overload @staticmethod def _encode_params(data: bytes) -> bytes: ... @overload @staticmethod def _encode_params( data: _t.SupportsRead[str | bytes], ) -> _t.SupportsRead[str | bytes]: ... @overload @staticmethod def _encode_params(data: _t.KVDataType) -> str: ... @staticmethod def _encode_params( data: _t.EncodableDataType, ) -> str | bytes | _t.SupportsRead[str | bytes]: """Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """ if isinstance(data, (str, bytes)): return data elif _t.has_read(data): return data elif hasattr(data, "__iter__"): result: list[tuple[bytes, bytes]] = [] for k, vs in to_key_val_list(data): if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): vs = [vs] for v in vs: if v is not None: result.append( ( k.encode("utf-8") if isinstance(k, str) else k, v.encode("utf-8") if isinstance(v, str) else v, ) ) return urlencode(result, doseq=True) else: return data # type: ignore[return-value] # unreachable for valid _t.DataType @staticmethod def _encode_files( files: _t.FilesType, data: _t.RawDataType | None ) -> tuple[bytes, str]: """Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). """ if not files: raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields: list[RequestField | tuple[str, bytes]] = [] fields = to_key_val_list(data or {}) files = to_key_val_list(files or {}) for field, val in fields: if isinstance(val, basestring) or not hasattr(val, "__iter__"): val = [val] for v in val: if v is not None: # Don't call str() on bytestrings: in Py3 it all goes wrong. if not isinstance(v, bytes): v = str(v) new_fields.append( ( field.decode("utf-8") if isinstance(field, bytes) else field, v.encode("utf-8") if isinstance(v, str) else v, ) ) for k, v in files: # support for explicit filename ft = None fh = None if isinstance(v, (tuple, list)): a = 1 b = 1 c = 1 d = 2 if len(v) == (a + b): fn, fp = v elif len(v) == (c + d): fn, fp, ft = v else: fn, fp, ft, fh = v else: fn = guess_filename(v) or k fp = v if isinstance(fp, (str, bytes, bytearray)): fdata = fp elif _t.has_read(fp): fdata = fp.read() elif fp is None: # defensive check for untyped callers continue else: fdata = fp rf = RequestField(name=k, data=fdata, filename=fn, headers=fh) rf.make_multipart(content_type=ft) new_fields.append(rf) body, content_type = encode_multipart_formdata(new_fields) return body, content_type

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.6853.095−226.152
Source linesThe number of non-empty source lines.218+87.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.254−6.381

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.219−6.718
Indentation frequencyHow rapidly indentation changes from line to line.201+6.215
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.201−4.191
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.217.938+2.637
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.95.954+0.744
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.95.968−0.4
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.067+0.29

Intercept 0.07 + feature contributions = -1.354 (log-odds).
Score = sigmoid(-1.354) = 0.205.

Score0.561
Score100
Run 1

The code has clear structure with logical class organization and good type hints, but suffers from several readability issues. The `_encode_params` method has excessive type overloads that clutter the beginning, and the parameter encoding logic uses nested conditionals that could be flattened. The `_encode_files` method has problematic magic numbers (`a = 1, b = 1, c = 1, d = 2`) instead of clear constants, making tuple validation unclear. Variable names like `ft`, `fh`, `fn`, `fp`, `rf` are cryptic. The file handling section uses else-if chains that require careful reading. The action granularity is mostly good with one operation per line, but some comprehensions pack multiple actions. Import organization is clean and docstrings are helpful, but the overall reading flow is interrupted by the awkward tuple-length checking logic and context switching between type declarations and implementation.

Run 2

The code has some strengths: docstrings are helpful, imports are organized, and type hints improve clarity. However, it suffers from several readability issues. The `_encode_params` method uses confusing `overload` decorators which add complexity without immediate benefit. The conditional logic in `_encode_files` is deeply nested and uses obscure arithmetic comparisons (`len(v) == (a + b)`) instead of simply comparing to 2 or 3, making the intent unclear. Variables like `a`, `b`, `c`, `d` are poorly named and add unnecessary indirection. Multiple actions occur on some lines, and error handling is abrupt. The code is overly long for its purpose and mixes concerns within single methods. While structure is adequate, nesting depth and poor variable names significantly reduce readability.

Run 3

The code is well-structured and readable, with clear organization via mixins and logical method grouping. Import section is extensive but alphabetized and grouped, which aids navigation. Most methods follow a flat structure with minimal nesting—the deepest nesting occurs in _encode_files but remains manageable. Intent is clearly documented with thorough docstrings explaining edge cases (e.g., type handling for parameters and files). Code length is appropriate given the complexity of multipart/form-data encoding and type overloads. Action granularity is generally good, though some lines in _encode_files combine multiple operations (e.g., tuple unpacking with conditional assignment). Reading flow is natural, with helper functions like to_key_val_list and RequestField abstracting lower-level details. Minor issues include the use of magic numbers (a=1, b=1, c=1, d=2) which obscures intent, and the defensive 'elif fp is None' check feels slightly awkward. Overall, this is production-quality code that balances type safety, backward compatibility, and clarity.

Run 1

Code Structure: Imports are grouped sensibly, and the mixin separates URL construction, parameter encoding, and multipart encoding into focused methods. Nesting: Encoding logic has several nested loops and conditionals, especially in _encode_files, increasing reading effort. Clarity of intent: Method names, docstrings, and type annotations explain the purpose well, but abbreviated variables such as k, vs, ft, and fp obscure details. The arbitrary a, b, c, and d variables used to calculate tuple lengths are particularly confusing. Code length: Mostly justified by input handling, although overloads, verbose branching, and unnecessary tuple-length arithmetic add bulk. Action granularity: Statements generally perform one action per line, with reasonable multiline formatting. Reading flow: Processing follows a natural validation-to-conversion-to-encoding sequence, but repeated type checks, compatibility details, and nested conditional expressions interrupt the flow.

Run 2

Code Structure: Imports, a focused mixin, and separate encoding methods provide logical organization. Nesting: Parameter and field encoding use several nested loops and conditionals, making these sections harder to scan. Clarity of intent: Docstrings, type annotations, and descriptive API names explain the purpose well, but abbreviated variables and arbitrary a, b, c, d assignments obscure simple tuple-length checks. Code length: Mostly justified by typing and input handling, though overloads add visual bulk and the arithmetic variables are unnecessary. Action granularity: Statements generally perform one action per line; tuple unpacking and inline conditional conversions remain reasonably clear. Reading flow: Methods progress naturally from validation through normalization to encoding, but the large import block, nested conversion expressions, and redundant arithmetic interrupt otherwise coherent flow.

Run 3

Code Structure: Imports, a focused mixin, and separate encoding methods provide logical organization. Nesting: Parameter and field processing use several nested loops and conditionals, making some paths harder to follow. Clarity of intent: Descriptive method names, docstrings, and type annotations explain the purpose well, but abbreviated variables and arbitrary a, b, c, d assignments obscure file-tuple handling. Code length: Most code is justified, though repeated conversion logic, extensive overload declarations, and unnecessary arithmetic add reading overhead. Action granularity: Statements generally perform one action per line; tuple unpacking and inline conditional conversions remain reasonably readable. Reading flow: Consistent formatting and sequential validation-to-encoding flow help comprehension, but long type signatures, nested expressions, and redundant elif/else branches after returns interrupt the flow.