Sample

pyint-cb5bcf6d3ffa-I10

Deterministically remove some optional blank lines and bracketed line breaks

Matched original source

Lines179

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1320–1; higher is more readable
Mi0.3360–1; higher is more readable
LLOC96Logical lines; fewer is more readable
DeepSeek V4 Pro9.330–20; mean of three runs
GPT-6.1 Sol13.670–20; mean of three runs
BTTF0.250–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)): if len(v) == 2: fn, fp = v elif len(v) == 3: 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.6667.363−220.023
Source linesThe number of non-empty source lines.179+71.6
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.258−6.387

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.180−5.337
Indentation frequencyHow rapidly indentation changes from line to line.162+4.866
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.162−3.297
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.178.917+2.091
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.130.939−1.881
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.130.989+1.309
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.066+0.298

Intercept 0.07 + feature contributions = -1.88 (log-odds).
Score = sigmoid(-1.88) = 0.132.

Score0.336
Score96
Run 1

The code has clear structure overall (class, properties, methods), but readability is hampered by inconsistent import formatting, excessive vertical spacing in imports, and some awkward line breaks (e.g., `__iter__` splitting). Nested logic in `_encode_params` and `_encode_files` creates moderate depth, though each action is reasonably granular. Intent is mostly clear, but long type annotations and overloads add noise. The `_encode_files` method is quite long (40+ lines) and handles multiple concerns, reducing scanability. The inconsistent alignment of imports and overly spacious line breaks disrupt reading flow. Some comments are helpful, but the code density and formatting inconsistencies prevent higher readability.

Run 2

The code has serious readability problems stemming primarily from formatting, not logic. Inconsistent alignment and spacing in imports (e.g., multiple spaces between names, trailing commas placed oddly) create visual noise. Functions like _encode_files contain deeply nested conditionals (especially the tuple-length handling inside a for loop) and multiple actions crammed onto single lines or awkward line breaks, reducing clarity. The `path_url` property is relatively clear, but `_encode_params` mixes type checking, iteration, and encoding logic with an `if/elif/else` chain containing nested loops. Line lengths and broken indentation (e.g., in `_encode_files` signature and tuple construction) hurt the reading flow. While the code's purpose—encoding parameters and files for requests—is understandable from names and docstrings, the actual implementation requires slow, effortful parsing due to poor structural organization and inconsistent formatting. It violates several criteria: action granularity is poor, nesting is deep, and the import section is disorganized.

Run 3

The code has some readable elements like descriptive method names and docstrings, but overall readability is poor. Imports are inconsistently formatted with odd spacing. Multiple function overloads add complexity but are logically organized. However, the main methods contain deeply nested conditionals, especially _encode_files with its tuple-unpacking logic. The _encode_params method mixes type checking with data transformation, making intent unclear. Line lengths are inconsistent with some very long multi-purpose lines. The multipart tuple handling (2-tuple, 3-tuple, 4-tuple) lacks explanatory comments and has ambiguous variable names like 'ft' and 'fh'. The reading flow is disrupted by excessive vertical spacing in some imports and cramped code in methods. While not the worst code, it falls below average readability standards.

Run 1

Code Structure: Responsibilities are logically grouped within an encoding mixin, with separate methods for URL paths, parameters, and multipart files. Nesting: Parameter and file encoding contain several nested loops and conditionals, increasing cognitive load. Clarity of intent: Method names, docstrings, and type annotations explain the purpose well, but abbreviated variables such as k, vs, fn, fp, ft, and fh obscure details. Code length: Mostly justified by supported input variants, though overloads and extensive imports add visual bulk. Action granularity: Most lines perform a single action; tuple unpacking and inline conditional expressions remain reasonably understandable. Reading flow: Processing generally follows a natural validation-to-transformation sequence, but inconsistent spacing, awkward import formatting, and malformed-looking line wrapping interrupt scanning. Overall, the code is understandable but would benefit from consistent formatting, descriptive local names, and reduced nesting.

Run 2

Code Structure: Related encoding operations are logically grouped in a mixin with separate methods, although the extensive import block adds clutter. Nesting: Parameter and multipart encoding contain 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; abbreviated variables such as k, vs, fn, fp, ft, and fh weaken local clarity. Code length: Mostly justified by supported input formats, but repeated normalization logic and overload declarations increase reading effort. Action granularity: Generally one operation per line, with tuple unpacking and conditional expressions remaining manageable. Reading flow: Processing follows a natural sequence from validation through normalization to encoding, but inconsistent whitespace, awkward line wrapping, and crowded imports interrupt scanning.

Run 3

Code Structure: Related URL and request-encoding operations are logically grouped in a mixin with separate methods, although imports are visually cluttered. Nesting: Encoding methods contain several nested loops and conditionals, especially multipart field handling, increasing reading effort. Clarity of intent: Method names, docstrings, type annotations, and comments explain purpose well; abbreviated variables such as k, vs, fn, fp, ft, and fh obscure details. Code length: Mostly justified by supported input formats, but overload declarations and repeated normalization logic add visual bulk. Action granularity: Most statements perform one action per line; tuple unpacking and conditional expressions remain manageable, though malformed spacing makes some expressions difficult to scan. Reading flow: Processing generally follows a natural sequence from validation through normalization to encoding, but inconsistent import formatting, excessive inline whitespace, and uneven spacing between declarations interrupt the flow.