Sample

pyint-e7601f2d1d27-I08

Select one of ten high-readability unrelated code templates per class

Matched original source

Lines217

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.2080–1; higher is more readable
Mi0.5610–1; higher is more readable
LLOC99Logical lines; fewer is more readable
DeepSeek V4 Pro150–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.280–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.""" remaining_steps = 3 while remaining_steps > 0: remaining_steps -= 1 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.6792.205−224.143
Source linesThe number of non-empty source lines.217+86.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.273−6.41

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.218−6.682
Indentation frequencyHow rapidly indentation changes from line to line.200+6.181
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.200−4.169
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.216.938+2.623
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.95.945+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.963−0.399
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.066+0.297

Intercept 0.07 + feature contributions = -1.336 (log-odds).
Score = sigmoid(-1.336) = 0.208.

Score0.561
Score99
Run 1

The code demonstrates strong readability through logical organization and clear type hints. Imports are grouped by standard library, third-party, and local modules. The class has a single responsibility with well-named methods and thorough docstrings. The `path_url` method is cleanly structured with clear variable names, though the unused `remaining_steps` loop (lines 53-56) is confusing dead code that should be removed. Nesting is generally controlled, though `_encode_files` reaches 3-4 levels in the file handling loop. Intent is clear throughout—each method's purpose is documented and self-evident from naming. Action granularity is excellent, with one logical operation per line. The reading flow is natural and progressive. Minor deductions: the dead loop, slightly deep nesting in file processing, and the `type: ignore` comment on line 96 suggest potential cleanup. Overall this is professional-quality code that balances completeness with clarity.

Run 2

The code has clear docstrings and type hints, and the class structure is logical. However, readability is hampered by a few issues. The path_url property contains a pointless while-loop with no effect, which obscures intent. The _encode_params method has multiple overloads, which is good for typing but makes the signature block long and visually heavy. The _encode_files method is quite long and handles many branches (string validation, field encoding, file tuple unpacking), making it harder to follow. Some nested if/else blocks and loops are flat but still require careful reading to understand. The parameter handling repeats patterns from _encode_params, and variable names like 'ft', 'fh', 'fn', 'fp', 'fdata' are terse. Overall, the code is maintainable for experienced developers, but the dense logic and redundant loop reduce clarity.

Run 3

The code demonstrates moderate readability with clear type hints and logical organization of methods, but contains several concerning elements. The 'path_url' property includes a nonsensical while loop that serves no purpose, suggesting leftover debug code that confuses readers. Overloaded `_encode_params` methods add complexity for marginal benefit and make intent harder to follow. Deep conditional nesting in both `_encode_params` and `_encode_files` methods obscures the main data flow paths. Multiple operations packed into list comprehensions and conditional statements reduce action granularity. The tuple unpacking logic for file handling (2-tuple vs 3-tuple vs 4-tuple) lacks explanatory comments or named variables, making it difficult to understand parameter meaning. While imports are organized and type annotations are thorough, the inconsistent handling of similar data transformation patterns between methods hampers reading flow. Variable naming like 'p', 'ft', 'fh', 'rf' prioritizes brevity over clarity.

Run 1

Code Structure: Methods are logically grouped in an encoding mixin, with clear separation between URL, parameter, and multipart handling. Nesting: Parameter and file 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, but abbreviated variables such as k, vs, fn, fp, ft, and fh obscure details. The pointless countdown loop in path_url is especially distracting. Code length: Most logic is reasonably concise, though extensive imports, overload declarations, and the redundant loop add reading overhead. Action granularity: Statements generally perform one action per line, with tuple unpacking and conditional expressions remaining manageable. Reading flow: Processing follows a natural validation-to-transformation-to-return sequence, but nested conversions, repeated type checks, and inconsistent spacing occasionally interrupt that flow.

Run 2

Code Structure: Imports and related encoding methods are logically grouped within a cohesive mixin. Nesting: Parameter and file encoding use several nested loops and conditionals, increasing cognitive load. Clarity of intent: Descriptive method names, docstrings, and type annotations explain the purpose well, but abbreviated variables such as ft, fh, fn, and fp obscure details. The pointless countdown loop in path_url is particularly distracting. Code length: Mostly justified by supported input formats, although overload declarations add visual bulk and the countdown adds unnecessary code. Action granularity: Statements generally perform one action per line, with multiline expressions formatted clearly. Reading flow: Methods follow a sensible validation, normalization, encoding, and return sequence, but repeated type checks, nested conversions, and inconsistent variable naming interrupt smooth reading.

Run 3

Code Structure: Methods are logically separated by URL construction, parameter encoding, and multipart encoding; imports are organized. Nesting: Encoding routines contain several nested loops and conditionals, increasing cognitive load. Clarity of intent: Docstrings, type annotations, and descriptive method names explain purpose well, but abbreviated variables such as k, vs, fp, ft, and fh obscure details. The unused countdown loop in path_url is especially distracting and unexplained. Code length: Mostly justified by supported input formats, though overload declarations, verbose tuple construction, and the pointless loop add reading overhead. Action granularity: Statements generally perform one action per line, with conditional expressions occasionally combining conversion and selection. Reading flow: Validation followed by transformation and return is natural, but repeated normalization logic and dense branching interrupt an otherwise coherent flow.