Sample

pyint-554d82fc50e3-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines222

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1980–1; higher is more readable
Mi0.5610–1; higher is more readable
LLOC100Logical lines; fewer is more readable
DeepSeek V4 Pro100–20; mean of three runs
GPT-6.1 Sol12.670–20; mean of three runs
BTTF0.2760–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 (not path): pass else: path = "/" url.append(path) query = p.query if not (query): pass else: 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 not (isinstance(val, basestring) or not hasattr(val, "__iter__")): pass else: val = [val] for v in val: if not (v is not None): pass else: # 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 not (isinstance(v, (tuple, list))): fn = guess_filename(v) or k fp = v else: if len(v) == 2: fn, fp = v elif len(v) == 3: fn, fp, ft = v else: fn, fp, ft, fh = 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.6877.14−226.946
Source linesThe number of non-empty source lines.222+88.8
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.239−6.358

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.223−6.859
Indentation frequencyHow rapidly indentation changes from line to line.205+6.354
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.205−4.283
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.221.938+2.692
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.95.556+0.737
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.942−0.398
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.067+0.291

Intercept 0.07 + feature contributions = -1.397 (log-odds).
Score = sigmoid(-1.397) = 0.198.

Score0.561
Score100
Run 1

The code has clear type hints and docstrings but suffers from several readability issues. The imports are organized but lengthy, taking up nearly half the file. The path_url property uses inverted conditionals (if not (not path)) that obscure intent, making simple logic needlessly complex. The _encode_params method has extremely long lines and nested comprehensions that reduce clarity. _encode_files contains deep nesting with multiple conditional branches and counterintuitive empty pass blocks alongside else clauses. Variable names like p, v, fp, ft, fh are cryptic without context. The action granularity is inconsistent - some lines pack multiple operations while others spread simple logic across many lines. Reading flow is disrupted by the unnatural conditional structures and heavy type annotation clutter. Structure improvements, clearer conditionals, and better naming would significantly improve readability.

Run 2

The code shows mixed readability. Imports are well-organized and type hints are extensive, which aids clarity. However, several areas significantly hurt readability: The path_url property uses awkward double-negative conditions like `if not (not path): pass else:`, which obscures intent. Similar inverted logic appears throughout _encode_files and _encode_params with empty pass branches that force readers to mentally reverse conditions. The _encode_params method has deep nesting and complex type handling that could be broken into smaller helpers. Some methods are long and try to do too much, particularly _encode_files. While the docstrings are helpful and variable names are mostly descriptive, the inverted conditionals and pass-else patterns create confusing reading flow. Action granularity is generally good, but the control flow structure makes the code unnecessarily difficult to follow.

Run 3

The code demonstrates poor readability due to several factors. The most glaring issue is the inverted conditional logic in multiple places (e.g., `if not (not path): pass else: path = "/"` and `if not (isinstance(v, basestring)...): pass else: val = [val]`), which creates unnecessary nesting depth and cognitive load. These patterns should use simple positive conditions. The `path_url` property has odd empty blocks and multiple actions that could be simplified. Function signatures are heavily overloaded, which adds complexity but is somewhat justified for type safety. Import statements are extensive but organized logically. The `_encode_files` method is particularly long with deeply nested conditionals and variable assignments that obscure the data flow. Variable names like `ft`, `fh`, `fp`, `fn` are cryptic. The code has good docstrings but the actual implementation contradicts the clarity they provide. Type hints are used extensively but sometimes add visual noise. Overall structure follows a logical organization, but the internal logic flow and conditional patterns significantly hamper readability.

Run 1

Code Structure: Organized into a focused mixin with separate URL, parameter, and multipart encoding methods, although the extensive imports distract from the implementation. Nesting: Moderate to deep nesting in encoding loops and conditional branches makes multipart handling harder to follow. Clarity of intent: Descriptive method names, docstrings, and type annotations clarify purpose, but inverted conditions, double negatives, empty pass branches, and abbreviated variables obscure details. Code length: Overloads provide useful typing, but redundant if/pass/else patterns unnecessarily lengthen otherwise straightforward logic. Action granularity: Most lines perform a single action, with tuple construction and inline conditional conversions adding some density. Reading flow: Method organization and spacing are consistent, but unnatural condition phrasing and nested alternatives interrupt the flow and require extra mental effort.

Run 2

Code Structure: Imports, a focused mixin, and separate encoding methods provide logical organization. Nesting: Parameter and file processing involve several nested loops and conditionals, increasing cognitive load. Clarity of intent: Method names, docstrings, and type annotations explain the purpose well, but inverted conditions, double negatives, and empty pass branches obscure straightforward decisions; abbreviated variables also reduce clarity. Code length: Most implementation detail is justified, though redundant conditional branches and extensive typing declarations make the snippet longer to scan. Action granularity: Statements generally perform one action per line, with clearly formatted tuple construction and function calls. Reading flow: Methods follow a sensible input-validation-to-processing-to-return sequence, but repeated 'if not ...: pass; else: ...' patterns interrupt natural reading. Overall, the code is understandable and organized, but unnecessarily convoluted conditionals prevent a higher score.

Run 3

Code Structure: Imports, a focused mixin, and separate encoding methods provide logical organization. Nesting: Parameter and file encoding contain several nested loops and conditionals, making some paths harder to follow. Clarity of intent: Method names, docstrings, and type annotations explain the purpose, but inverted conditions, double negatives, empty pass branches, and abbreviated variables obscure otherwise simple logic. Code length: The implementation is moderately concise, although redundant branches and extensive typing declarations increase reading overhead. Action granularity: Most lines perform one action; tuple unpacking and conditional expressions remain reasonably understandable. Reading flow: Methods follow a sensible progression from validation to transformation and return, but unnecessary else branches and negated tests repeatedly interrupt that flow. Overall, the code is understandable but would benefit substantially from direct conditions, guard clauses, and clearer local names.