Sample

pyint-8fc2acb2f957-I12

Inline all eligible single-use intermediate local variables

Matched original source

Lines214

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.2130–1; higher is more readable
Mi0.5610–1; higher is more readable
LLOC96Logical lines; fewer is more readable
DeepSeek V4 Pro14.330–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.3030–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.214+85.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.274−6.411

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.215−6.576
Indentation frequencyHow rapidly indentation changes from line to line.197+6.077
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.197−4.1
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.213.928+2.58
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.95.94+0.743
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.949−0.399
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.067+0.295

Intercept 0.07 + feature contributions = -1.308 (log-odds).
Score = sigmoid(-1.308) = 0.213.

Score0.561
Score96
Run 1

The code shows good organization with clear sectioning through imports and class methods, but has several readability issues. The type hinting is excellent and adds clarity. However, some methods are quite long and combine multiple logical operations. The _encode_files method is particularly dense with nested conditionals (4-5 levels deep) and tuple unpacking that requires careful reading. The _encode_params method has a confusing overload structure. Variable names are often too short ('p', 'k', 'v', 'fn', 'fp', 'ft', 'fh') and don't clearly communicate intent. Some lines perform multiple operations, especially in list comprehensions and tuple assignments. The error handling is clear, but the overall flow in longer methods requires careful tracking of state. While type annotations and docstrings help, the code would benefit from extracting helper methods and using more descriptive variable names. The import section is cleanly organized but very long, suggesting potential code organization issues at the module level.

Run 2

The code is generally well-structured with clear docstrings, logical imports, and reasonable action granularity. Type hints and overloads enhance clarity of intent. However, readability suffers in `_encode_params` and `_encode_files` due to deep nesting (up to 4 levels), repeated isinstance checks, and complex conditional logic. The `_encode_files` method is long and mixes multiple responsibilities (validation, field encoding, file handling), making it harder to follow. Some variable names (`vs`, `ft`, `fh`, `fn`, `fp`) are cryptic. The defensive `else: return data` branch in `_encode_params` is confusing despite the comment. While not unreadable, the code could benefit from extracting helper methods and flattening nested loops.

Run 3

The code is generally readable with clear type hints, descriptive variable names, and docstrings explaining purpose. However, it has several readability issues: deep nesting in _encode_files (4 levels of indentation), multiple actions packed into single lines (ternary expressions combined with function calls), and inconsistent code structure. The import section is excessively long with many grouped imports. The _encode_params method has overloaded signatures that add complexity but are well-organized. Some conditional branches are dense, particularly the tuple unpacking logic in _encode_files. The code mixes type checking, data transformation, and error handling in ways that could be separated. While type annotations and docstrings aid understanding, the actual logic flow requires careful reading to follow.

Run 1

Code Structure: Imports are grouped sensibly, and related encoding operations are organized into focused methods within a mixin. Nesting: Parameter and multipart encoding contain several nested loops and conditionals, increasing cognitive load. Clarity of intent: Descriptive method names, docstrings, comments, and type annotations explain purpose well, although abbreviated variables such as ft, fh, fp, and rf obscure details. Code length: Most implementation is justified, but extensive imports and overload declarations add visual bulk relative to the excerpt's functionality. Action granularity: Statements generally perform one action per line; tuple unpacking and inline conditional expressions are reasonable but occasionally dense. Reading flow: Methods follow a natural validation, normalization, encoding, and return sequence. Repeated normalization logic, redundant elif branches after returns, and multiline conditional expressions slightly interrupt that flow.

Run 2

Code Structure: Imports and related encoding operations are logically grouped in a cohesive mixin, though the extensive import block distracts from this excerpt. Nesting: Parameter and file encoding contain several nested loops and conditionals, making some paths harder to follow. Clarity of intent: Descriptive method names, docstrings, type annotations, and targeted comments explain purpose well; abbreviated variables such as k, vs, ft, fh, and fp reduce local clarity. Code length: Mostly justified by input flexibility, but overload declarations and repeated normalization logic add verbosity. Action granularity: Statements generally perform one action per line, with tuple construction and conditional expressions remaining reasonably readable. Reading flow: Validation, normalization, encoding, and return steps follow a natural sequence; polymorphic input handling and deeply indented expressions occasionally interrupt that flow.

Run 3

Code Structure: Responsibilities are logically grouped into a mixin with focused methods, though the extensive imports add overhead. Nesting: Parameter and file encoding contain nested loops and conditionals, reaching several levels and making transformations harder to follow. Clarity of intent: Method names, docstrings, annotations, and explanatory comments clearly describe the purpose; abbreviated variables such as ft, fh, fp, and rf reduce local clarity. Code length: Mostly justified by supported input formats and typing, but overload declarations and repeated normalization logic add verbosity. Action granularity: Statements generally perform one action per line, with readable formatting for complex expressions. Reading flow: Validation precedes processing, and encoding follows a natural sequence; inline conditional expressions, redundant elif branches after returns, and reused variables slightly interrupt the flow.