Sample

pyint-232e3838bfa8-I13

Lower every eligible synchronous for loop to a while loop

Matched original source

Lines224

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1930–1; higher is more readable
Mi0.5610–1; higher is more readable
LLOC104Logical lines; fewer is more readable
DeepSeek V4 Pro100–20; mean of three runs
GPT-6.1 Sol130–20; mean of three runs
BTTF0.2820–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]] = [] loopIteratorA = __import__("builtins").iter(to_key_val_list(data)) while True: try: k, vs = __import__("builtins").next(loopIteratorA) except __import__("builtins").StopIteration: break if isinstance(vs, basestring) or not hasattr(vs, "__iter__"): vs = [vs] loopIterator = __import__("builtins").iter(vs) while True: try: v = __import__("builtins").next(loopIterator) except __import__("builtins").StopIteration: break 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.7213.299−238.039
Source linesThe number of non-empty source lines.224+89.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.255−6.383

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.225−6.93
Indentation frequencyHow rapidly indentation changes from line to line.207+6.423
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.207−4.329
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.223.918+2.72
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.94.747+0.724
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.956−0.399
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.067+0.292

Intercept 0.07 + feature contributions = -1.429 (log-odds).
Score = sigmoid(-1.429) = 0.193.

Score0.561
Score104
Run 1

The code has good type hints, docstrings, and logical structure, but suffers from poor readability due to deep nesting and convoluted iteration patterns. The `_encode_params` method uses manual while loops with `__import__('builtins')` instead of standard Python constructs, which obscures intent and adds unnecessary complexity. The nested loops for processing key-value pairs and files create multiple levels of indentation, making the flow harder to follow. While the code is functionally organized, the manual iteration and explicit exception handling for `StopIteration` are unidiomatic and reduce clarity. The `_encode_files` method is clearer but still has non-obvious variable names (`fn`, `fp`, `ft`, `fh`) and inline conditional logic that hampers readability. Overall, the code demonstrates good structural organization and typing, but the implementation choices significantly impair readability and maintainability.

Run 2

The code has clear type hints and docstrings, but readability is severely compromised by several factors: (1) the `_encode_params` method uses convoluted `__import__('builtins').next()` calls instead of Python's normal `for` loops or `next()` builtin, making it unnecessarily obscure; (2) deep nesting in `_encode_files` (up to 4 levels) with multiple conditional branches obscures flow; (3) multiple actions are packed into single lines, violating one-action-per-line granularity; (4) `_encode_files` mixes tuple unpacking, type checks, and object construction in tight blocks, making it hard to follow; (5) excessive type checking (`isinstance`, `hasattr`) creates repetitive, noisy logic; (6) the `while True` with explicit `StopIteration` catching is a low-level pattern that breaks natural reading flow. While imports are organized and classes/methods are logically grouped, the core logic is tangled and requires significant mental effort to parse.

Run 3

The code has clear structure and good documentation but suffers from readability issues in specific areas. The class organization is logical, and type hints are comprehensive. However, the _encode_params method uses awkward manual iteration with __import__('builtins') instead of standard Python constructs, which significantly harms clarity. The nested while loops with try-except for StopIteration create unnecessary depth and obscure intent. Action granularity is inconsistent - some lines pack multiple operations while others are over-verbose. The _encode_files method is more readable with clearer flow but still has moderately deep nesting. The extensive imports and type annotations add visual noise but serve documentation purposes. Overall, the code demonstrates professional quality with good docstrings and error handling, but the non-idiomatic iteration pattern and inconsistent nesting prevent it from being highly readable.

Run 1

Code Structure: Methods logically separate URL construction, parameter encoding, and multipart encoding, with helpful docstrings and type annotations. Nesting: Encoding methods contain several nested loops and conditionals; explicit iterator loops with try/except add avoidable depth. Clarity of intent: Method names and documentation explain purposes, but abbreviated variables such as k, vs, ft, and fh obscure details. Repeated dynamic imports of builtins make ordinary iteration unnecessarily difficult to interpret. Code length: The large import block, overload declarations, and expanded iterator handling increase reading overhead; standard for loops would substantially simplify _encode_params. Action granularity: Statements generally perform one action per line, although conditional expressions inside tuple construction require extra parsing. Reading flow: Formatting and method boundaries support sequential reading, but exception-driven iteration interrupts the flow, and multipart handling requires tracking several short-named variables across branches. Overall, the organization is sound, but localized verbosity and complexity noticeably reduce readability.

Run 2

Code Structure: Imports, a focused mixin, and separate encoding methods provide logical organization. Nesting: Multipart processing has moderate nesting, while parameter encoding adds unnecessary nested while/try/except blocks. Clarity of intent: Method names, docstrings, and type annotations explain the purpose, but abbreviated variables and repeated dynamic builtins imports obscure straightforward iteration. Code length: Extensive imports and overloads add visual overhead; manually implementing iterator advancement makes _encode_params substantially longer than necessary. Action granularity: Most lines perform one action, with tuple unpacking and conditional expressions remaining reasonably readable. Reading flow: Formatting and method boundaries support navigation, but artificial loop machinery interrupts natural flow and distracts from the encoding logic. Overall, the code is understandable, yet avoidable iteration complexity noticeably reduces readability.

Run 3

Code Structure: Imports, a focused mixin, and separate encoding methods provide logical organization. Nesting: Multipart encoding has moderate nesting, while parameter encoding becomes unnecessarily deep through nested while loops and try/except blocks. Clarity of intent: Method names, docstrings, and type annotations explain the purpose, but abbreviated variables and generic iterator names obscure details. Code length: Extensive imports and overloads add overhead; manually implementing iteration with repeated __import__("builtins") calls is substantially more verbose than ordinary for loops. Action granularity: Most statements perform one action per line, although conditional expressions inside tuple construction require extra parsing. Reading flow: Validation, normalization, and encoding generally follow a natural sequence, but the unusual iterator machinery interrupts that flow and distracts from otherwise straightforward logic.