Sample

pyint-549c5b3ccd1f-I05

Rewrite eligible decimal integer literals in hexadecimal notation

Matched original source

Lines270

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1050–1; higher is more readable
Mi0.5830–1; higher is more readable
LLOC73Logical lines; fewer is more readable
DeepSeek V4 Pro12.330–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.4450–1; higher is more readable

Views

Source code

from __future__ import annotations import abc import contextlib import enum import itertools import linecache import sys import types import unicodedata import weakref from collections.abc import Callable, Mapping from functools import cached_property from typing import Any, NamedTuple, TypeVar from . import _compat, _config, setters from ._compat import ( PY_3_11_PLUS, PY_3_13_PLUS, _AnnotationExtractor, _get_annotations, _lazy_is_generator, get_generic_base, ) from .exceptions import ( DefaultAlreadySetError, FrozenInstanceError, NotAnAttrsClassError, UnannotatedAttributeError, ) class Attribute: """ *Read-only* representation of an attribute. .. warning:: You should never instantiate this class yourself. The class has *all* arguments of `attr.ib` (except for ``factory`` which is only syntactic sugar for ``default=Factory(...)`` plus the following: - ``name`` (`str`): The name of the attribute. - ``alias`` (`str`): The __init__ parameter name of the attribute, after any explicit overrides and default private-attribute-name handling. - ``alias_is_default`` (`bool`): Whether the ``alias`` was automatically generated (``True``) or explicitly provided by the user (``False``). - ``inherited`` (`bool`): Whether or not that attribute has been inherited from a base class. - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The callables that are used for comparing and ordering objects by this attribute, respectively. These are set by passing a callable to `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also :ref:`comparison customization <custom-comparison>`. Instances of this class are frequently used for introspection purposes like: - `fields` returns a tuple of them. - Validators get them passed as the first argument. - The :ref:`field transformer <transform-fields>` hook receives a list of them. - The ``alias`` property exposes the __init__ parameter name of the field, with any overrides and default private-attribute handling applied. .. versionadded:: 20.1.0 *inherited* .. versionadded:: 20.1.0 *on_setattr* .. versionchanged:: 20.2.0 *inherited* is not taken into account for equality checks and hashing anymore. .. versionadded:: 21.1.0 *eq_key* and *order_key* .. versionadded:: 22.2.0 *alias* .. versionadded:: 26.1.0 *alias_is_default* For the full version history of the fields, see `attr.ib`. """ # These slots must NOT be reordered because we use them later for # instantiation. __slots__ = ( # noqa: RUF023 "name", "default", "validator", "repr", "eq", "eq_key", "order", "order_key", "hash", "init", "metadata", "type", "converter", "kw_only", "inherited", "on_setattr", "alias", "alias_is_default", ) def __init__( self, name, default, validator, repr, cmp, # XXX: unused, remove along with other cmp code. hash, init, inherited, metadata=None, type=None, converter=None, kw_only=False, eq=None, eq_key=None, order=None, order_key=None, on_setattr=None, alias=None, alias_is_default=None, ): eq, eq_key, order, order_key = _determine_attrib_eq_order( cmp, eq_key or eq, order_key or order, True ) # Cache this descriptor here to speed things up later. bound_setattr = _OBJ_SETATTR.__get__(self) # Despite the big red warning, people *do* instantiate `Attribute` # themselves. bound_setattr("name", name) bound_setattr("default", default) bound_setattr("validator", validator) bound_setattr("repr", repr) bound_setattr("eq", eq) bound_setattr("eq_key", eq_key) bound_setattr("order", order) bound_setattr("order_key", order_key) bound_setattr("hash", hash) bound_setattr("init", init) bound_setattr("converter", converter) bound_setattr( "metadata", ( types.MappingProxyType(dict(metadata)) # Shallow copy if metadata else _EMPTY_METADATA_SINGLETON ), ) bound_setattr("type", type) bound_setattr("kw_only", kw_only) bound_setattr("inherited", inherited) bound_setattr("on_setattr", on_setattr) bound_setattr("alias", alias) bound_setattr( "alias_is_default", alias is None if alias_is_default is None else alias_is_default, ) def __setattr__(self, name, value): raise FrozenInstanceError @classmethod def from_counting_attr( cls, name: str, ca: _CountingAttr, kw_only: bool, type=None ): # The 'kw_only' argument is the class-level setting, and is used if the # attribute itself does not explicitly set 'kw_only'. # type holds the annotated value. deal with conflicts: if type is None: type = ca.type elif ca.type is not None: msg = f"Type annotation and type argument cannot both be present for '{name}'." raise ValueError(msg) return cls( name, ca._default, ca._validator, ca.repr, None, ca.hash, ca.init, False, ca.metadata, type, ca._converter, kw_only if ca.kw_only is None else ca.kw_only, ca.eq, ca.eq_key, ca.order, ca.order_key, ca.on_setattr, ca.alias, ca.alias is None, ) # Don't use attrs.evolve since fields(Attribute) doesn't work def evolve(self, **changes): """ Copy *self* and apply *changes*. This works similarly to `attrs.evolve` but that function does not work with :class:`attrs.Attribute`. It is mainly meant to be used for `transform-fields`. .. versionadded:: 20.3.0 """ import copy new = copy.copy(self) new._setattrs(changes.items()) if "alias" in changes and "alias_is_default" not in changes: # Explicit alias provided -- no longer the default. _OBJ_SETATTR.__get__(new)("alias_is_default", False) elif ( "name" in changes and "alias" not in changes # Don't auto-generate alias if the user picked picked the old one. and self.alias_is_default ): # Name changed, alias was auto-generated -- update it. _OBJ_SETATTR.__get__(new)( "alias", _default_init_alias_for(new.name) ) return new # Don't use _add_pickle since fields(Attribute) doesn't work def __getstate__(self): """ Play nice with pickle. """ return tuple( getattr(self, name) if name != "metadata" else dict(self.metadata) for name in self.__slots__ ) def __setstate__(self, state): """ Play nice with pickle. """ if len(state) < len(self.__slots__): # Pre-26.1.0 pickle without alias_is_default -- infer it # heuristically. state_dict = dict(zip(self.__slots__, state, strict=False)) alias_is_default = state_dict.get( "alias" ) is None or state_dict.get("alias") == _default_init_alias_for( state_dict["name"] ) state = (*state, alias_is_default) self._setattrs(zip(self.__slots__, state, strict=True)) def _setattrs(self, name_values_pairs): bound_setattr = _OBJ_SETATTR.__get__(self) for name, value in name_values_pairs: if name != "metadata": bound_setattr(name, value) else: bound_setattr( name, ( types.MappingProxyType(dict(value)) if value else _EMPTY_METADATA_SINGLETON ), )

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.5522.817−182.253
Source linesThe number of non-empty source lines.270+108
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.383−6.575

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.271−8.559
Indentation frequencyHow rapidly indentation changes from line to line.196+6.042
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.196−4.077
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.269.957+3.364
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.90.978+0.663
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.041+0.541
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.90.956−0.187

Intercept 0.07 + feature contributions = -2.143 (log-odds).
Score = sigmoid(-2.143) = 0.105.

Score0.583
Score73
Run 1

The code is moderately readable. It has clear structure with a well-documented class, logical method organization, and good use of slots/type hints. However, it loses points due to long methods with many steps (__init__, evolve), repetitive bound_setattr calls that add vertical length without clarity, and some magic/complex conditional logic (alias_is_default handling). Nesting is generally flat, and intent is mostly clear, but the alias/alias_is_default interactions are subtle and not self-explanatory. The class docstring is thorough but very long. Action granularity is mostly one-per-line, which aids readability, but some lines pack multiple operations. Overall, it reads like mature library code with historical baggage; readable for maintainers but not immediately accessible to newcomers.

Run 2

The code is structurally clear at the class level and has helpful docstrings, but readability is severely hampered by heavy low-level machinery and inconsistent abstraction. The __init__ method relies on repeated bound_setattr calls and magic descriptors like _OBJ_SETATTR, making the simple act of setting fields obscure. Many parameters are positional, including a comment noting one is unused, which adds cognitive overhead. The nested conditional logic in evolve and __setstate__ is not deeply indented but is difficult to follow due to reliance on internal state manipulation, zip trickery, and special-case handling. The module-level imports include several unused or conditional names, further muddying intent. While the code is dense and avoids excessive length, the one-action-per-line style actually works against clarity here because the operations are non-obvious. Overall, the code requires deep familiarity with the library’s internals to read confidently, making it accessible mainly to maintainers rather than general readers.

Run 3

The code demonstrates strong readability overall. Structure is logical: imports are organized, the class has a clear purpose, and methods are grouped meaningfully. Nesting is minimal—only a few conditional blocks exist, none deeply nested. Intent is clearly expressed through descriptive names (e.g., `from_counting_attr`, `alias_is_default`, `FrozenInstanceError`) and helpful docstrings with version history and warnings. Action granularity is mostly good, with one primary operation per line, though some lines like `bound_setattr('alias_is_default', alias is None if alias_is_default is None else alias_is_default)` combine logic. Length is reasonable—comprehensive but not bloated for the complexity the class represents. Reading flow is natural: the constructor progresses logically through attribute initialization, and the pickle/evolve methods are separated appropriately. Minor deductions: the `cmp` parameter marked unused is slightly confusing, some conditional expressions could be clearer, and the `_setattrs` method is concise but perhaps too terse without visible context. Overall, this is clean library code that balances documentation with implementation effectively.

Run 1

Code Structure: Methods are logically grouped around initialization, copying, serialization, and immutable attribute handling. Nesting: Mostly flat, with shallow conditionals and loops; multiline expressions add some visual complexity. Clarity of intent: Descriptive method names, extensive documentation, and explanatory comments make responsibilities clear, although private helpers and descriptor manipulation require background knowledge. Code length: Generally justified, but the lengthy documentation, repeated assignments, and large constructor increase reading effort. Action granularity: Most lines perform one action; tuple unpacking and conditional expressions remain reasonably focused. Reading flow: Consistent formatting and method organization support natural reading, but the long positional constructor call requires matching arguments manually, and slot-order dependencies plus awkwardly wrapped serialization logic interrupt the flow.

Run 2

Code Structure: Cohesive class with clearly separated initialization, copying, serialization, and internal assignment methods. Nesting: Mostly shallow; conditional expressions and multiline conditions add modest complexity. Clarity of intent: Descriptive method names, extensive documentation, and helpful comments explain behavior, though descriptor manipulation, external helpers, and the long positional constructor call require careful interpretation. Code length: Generally justified, but repetitive assignments, lengthy documentation, and compatibility handling increase reading effort. Action granularity: Operations are predominantly one per line, with clear separation between steps. Reading flow: Methods follow a logical sequence, but lengthy parameter lists, order-dependent slots, and awkward wrapping in pickle compatibility logic interrupt otherwise natural flow.

Run 3

Code Structure: Well-organized class with distinct initialization, construction, copying, and serialization methods. Nesting: Mostly shallow; conditional expressions and multiline calls add some visual complexity without deep nesting. Clarity of intent: Descriptive methods, extensive documentation, and explanatory comments clarify immutability and compatibility behavior. However, external helpers, abbreviated names such as ca, and the long positional constructor call require additional context. Code length: Generally justified, although lengthy documentation, repeated assignments, and duplicated metadata conversion make the excerpt verbose. Action granularity: Statements generally perform one action per line; tuple unpacking and conditional expressions remain manageable. Reading flow: Methods follow a sensible progression, but the large parameter list, order-sensitive slots, and awkward wrapping in pickle compatibility logic interrupt scanning.