Sample

pyint-557c4dac856c-I01

Remove comments and docstrings

Matched original source

Lines614

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0020–1; higher is more readable
Mi0.7120–1; higher is more readable
LLOC281Logical lines; fewer is more readable
DeepSeek V4 Pro110–20; mean of three runs
GPT-6.1 Sol13.670–20; mean of three runs
BTTF0.3080–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 _ClassBuilder: __slots__ = ( "_add_method_dunders", "_attr_names", "_attrs", "_base_attr_map", "_base_names", "_cache_hash", "_cls", "_cls_dict", "_delete_attribs", "_frozen", "_has_custom_setattr", "_has_post_init", "_has_pre_init", "_is_exc", "_on_setattr", "_pre_init_has_args", "_repr_added", "_script_snippets", "_slots", "_weakref_slot", "_wrote_own_setattr", ) def __init__( self, cls: type, these, auto_attribs: bool, props: ClassProps, has_custom_setattr: bool, ): attrs, base_attrs, base_map = _transform_attrs( cls, these, auto_attribs, props.kw_only, props.collected_fields_by_mro, props.field_transformer, ) self._cls = cls self._cls_dict = dict(cls.__dict__) if props.is_slotted else {} self._attrs = attrs self._base_names = {a.name for a in base_attrs} self._base_attr_map = base_map self._attr_names = tuple(a.name for a in attrs) self._slots = props.is_slotted self._frozen = props.is_frozen self._weakref_slot = props.has_weakref_slot self._cache_hash = ( props.hashability is ClassProps.Hashability.HASHABLE_CACHED ) self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False)) self._pre_init_has_args = False if self._has_pre_init: import inspect pre_init_func = cls.__attrs_pre_init__ pre_init_signature = inspect.signature(pre_init_func) self._pre_init_has_args = len(pre_init_signature.parameters) > 1 self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) self._delete_attribs = not bool(these) self._is_exc = props.is_exception self._on_setattr = props.on_setattr_hook self._has_custom_setattr = has_custom_setattr self._wrote_own_setattr = False self._cls_dict["__attrs_attrs__"] = self._attrs self._cls_dict["__attrs_props__"] = props if props.is_frozen: self._cls_dict["__setattr__"] = _frozen_setattrs self._cls_dict["__delattr__"] = _frozen_delattrs self._wrote_own_setattr = True elif self._on_setattr in ( _DEFAULT_ON_SETATTR, setters.validate, setters.convert, ): has_validator = has_converter = False for a in attrs: if a.validator is not None: has_validator = True if a.converter is not None: has_converter = True if has_validator and has_converter: break if ( ( self._on_setattr == _DEFAULT_ON_SETATTR and not (has_validator or has_converter) ) or (self._on_setattr == setters.validate and not has_validator) or (self._on_setattr == setters.convert and not has_converter) ): self._on_setattr = None if props.added_pickling: ( self._cls_dict["__getstate__"], self._cls_dict["__setstate__"], ) = self._make_getstate_setstate() self._script_snippets: list[ tuple[str, dict, Callable[[dict, dict], Any]] ] = [] self._repr_added = False if not hasattr(self._cls, "__module__") or not hasattr( self._cls, "__qualname__" ): self._add_method_dunders = self._add_method_dunders_safe else: self._add_method_dunders = self._add_method_dunders_unsafe def __repr__(self): return f"<_ClassBuilder(cls={self._cls.__name__})>" def _eval_snippets(self) -> None: script = "\n".join([snippet[0] for snippet in self._script_snippets]) globs = {} for _, snippet_globs, _ in self._script_snippets: globs.update(snippet_globs) locs = _linecache_and_compile( script, _generate_unique_filename(self._cls, "methods"), globs, ) for _, _, hook in self._script_snippets: hook(self._cls_dict, locs) def build_class(self): self._eval_snippets() if self._slots is True: cls = self._create_slots_class() self._cls.__attrs_base_of_slotted__ = weakref.ref(cls) else: cls = abc.update_abstractmethods(self._patch_original_class()) if ( getattr(cls, "__attrs_init_subclass__", None) and "__attrs_init_subclass__" not in cls.__dict__ ): cls.__attrs_init_subclass__() return cls def _patch_original_class(self): cls = self._cls base_names = self._base_names if self._delete_attribs: for name in self._attr_names: if ( name not in base_names and getattr(cls, name, _SENTINEL) is not _SENTINEL ): with contextlib.suppress(AttributeError): delattr(cls, name) for name, value in self._cls_dict.items(): setattr(cls, name, value) if not self._wrote_own_setattr and getattr( cls, "__attrs_own_setattr__", False ): cls.__attrs_own_setattr__ = False if not self._has_custom_setattr: cls.__setattr__ = _OBJ_SETATTR return cls def _create_slots_class(self): cd = { k: v for k, v in self._cls_dict.items() if k not in (*tuple(self._attr_names), "__dict__", "__weakref__") } if hasattr(sys, "_clear_type_descriptors"): sys._clear_type_descriptors(self._cls) if not self._wrote_own_setattr: cd["__attrs_own_setattr__"] = False if not self._has_custom_setattr: for base_cls in self._cls.__bases__: if base_cls.__dict__.get("__attrs_own_setattr__", False): cd["__setattr__"] = _OBJ_SETATTR break existing_slots = {} weakref_inherited = False for base_cls in self._cls.__mro__[1:-1]: if base_cls.__dict__.get("__weakref__", None) is not None: weakref_inherited = True existing_slots.update( { name: getattr(base_cls, name) for name in getattr(base_cls, "__slots__", []) } ) base_names = set(self._base_names) names = self._attr_names if ( self._weakref_slot and "__weakref__" not in getattr(self._cls, "__slots__", ()) and "__weakref__" not in names and not weakref_inherited ): names += ("__weakref__",) cached_properties = { name: cached_prop.func for name, cached_prop in cd.items() if isinstance(cached_prop, cached_property) } additional_closure_functions_to_update = [] if cached_properties: import inspect class_annotations = _get_annotations(self._cls) for name, func in cached_properties.items(): names += (name,) del cd[name] additional_closure_functions_to_update.append(func) annotation = inspect.signature(func).return_annotation if annotation is not inspect.Parameter.empty: class_annotations[name] = annotation original_getattr = cd.get("__getattr__") if original_getattr is not None: additional_closure_functions_to_update.append(original_getattr) cd["__getattr__"] = _make_cached_property_getattr( cached_properties, original_getattr, self._cls ) slot_names = [name for name in names if name not in base_names] reused_slots = { slot: slot_descriptor for slot, slot_descriptor in existing_slots.items() if slot in slot_names } slot_names = [name for name in slot_names if name not in reused_slots] cd.update(reused_slots) if self._cache_hash: slot_names.append(_HASH_CACHE_FIELD) cd["__slots__"] = tuple(slot_names) cd["__qualname__"] = self._cls.__qualname__ cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd) for item in itertools.chain( cls.__dict__.values(), additional_closure_functions_to_update ): if isinstance(item, (classmethod, staticmethod)): closure_cells = getattr(item.__func__, "__closure__", None) elif isinstance(item, property): closure_cells = getattr(item.fget, "__closure__", None) else: closure_cells = getattr(item, "__closure__", None) if not closure_cells: continue for cell in closure_cells: try: match = cell.cell_contents is self._cls except ValueError: pass else: if match: cell.cell_contents = cls return cls def add_repr(self, ns): script, globs = _make_repr_script(self._attrs, ns) def _attach_repr(cls_dict, globs): cls_dict["__repr__"] = self._add_method_dunders(globs["__repr__"]) self._script_snippets.append((script, globs, _attach_repr)) self._repr_added = True return self def add_str(self): if not self._repr_added: msg = "__str__ can only be generated if a __repr__ exists." raise ValueError(msg) def __str__(self): return self.__repr__() self._cls_dict["__str__"] = self._add_method_dunders(__str__) return self def _make_getstate_setstate(self): state_attr_names = tuple( an for an in self._attr_names if an != "__weakref__" ) def slots_getstate(self): return {name: getattr(self, name) for name in state_attr_names} hash_caching_enabled = self._cache_hash def slots_setstate(self, state): __bound_setattr = _OBJ_SETATTR.__get__(self) if isinstance(state, tuple): for name, value in zip(state_attr_names, state, strict=False): __bound_setattr(name, value) else: for name in state_attr_names: if name in state: __bound_setattr(name, state[name]) if hash_caching_enabled: __bound_setattr(_HASH_CACHE_FIELD, None) return slots_getstate, slots_setstate def make_unhashable(self): self._cls_dict["__hash__"] = None return self def add_hash(self): script, globs = _make_hash_script( self._cls, self._attrs, frozen=self._frozen, cache_hash=self._cache_hash, ) def attach_hash(cls_dict: dict, locs: dict) -> None: cls_dict["__hash__"] = self._add_method_dunders(locs["__hash__"]) self._script_snippets.append((script, globs, attach_hash)) return self def add_init(self): script, globs, annotations = _make_init_script( self._cls, self._attrs, self._has_pre_init, self._pre_init_has_args, self._has_post_init, self._frozen, self._slots, self._cache_hash, self._base_attr_map, self._is_exc, self._on_setattr, attrs_init=False, ) def _attach_init(cls_dict, globs): init = globs["__init__"] init.__annotations__ = annotations cls_dict["__init__"] = self._add_method_dunders(init) self._script_snippets.append((script, globs, _attach_init)) return self def add_replace(self): def __replace__(*args, **changes): return evolve(*args, **changes) self._cls_dict["__replace__"] = self._add_method_dunders(__replace__) return self def add_match_args(self): self._cls_dict["__match_args__"] = tuple( field.name for field in self._attrs if field.init and not field.kw_only ) def add_attrs_init(self): script, globs, annotations = _make_init_script( self._cls, self._attrs, self._has_pre_init, self._pre_init_has_args, self._has_post_init, self._frozen, self._slots, self._cache_hash, self._base_attr_map, self._is_exc, self._on_setattr, attrs_init=True, ) def _attach_attrs_init(cls_dict, globs): init = globs["__attrs_init__"] init.__annotations__ = annotations cls_dict["__attrs_init__"] = self._add_method_dunders(init) self._script_snippets.append((script, globs, _attach_attrs_init)) return self def add_eq(self): cd = self._cls_dict script, globs = _make_eq_script(self._attrs) def _attach_eq(cls_dict, globs): cls_dict["__eq__"] = self._add_method_dunders(globs["__eq__"]) self._script_snippets.append((script, globs, _attach_eq)) cd["__ne__"] = __ne__ return self def add_order(self): cd = self._cls_dict cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = ( self._add_method_dunders(meth) for meth in _make_order(self._cls, self._attrs) ) return self def add_setattr(self): sa_attrs = {} for a in self._attrs: on_setattr = a.on_setattr or self._on_setattr if on_setattr and on_setattr is not setters.NO_OP: sa_attrs[a.name] = ( a, on_setattr, _lazy_is_generator(on_setattr), ) if not sa_attrs: return self if self._has_custom_setattr: msg = "Can't combine custom __setattr__ with on_setattr hooks." raise ValueError(msg) def __setattr__(self, name, val): try: a, hook, is_gen = sa_attrs[name] except KeyError: _OBJ_SETATTR(self, name, val) return if is_gen(): gen = hook(self, a, val) nval = next(gen) _OBJ_SETATTR(self, name, nval) try: next(gen) except StopIteration: return gen.close() msg = "Generator on_setattr hook yielded more than once." raise RuntimeError(msg) nval = hook(self, a, val) _OBJ_SETATTR(self, name, nval) return self._cls_dict["__attrs_own_setattr__"] = True self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__) self._wrote_own_setattr = True return self def _add_method_dunders_unsafe(self, method: Callable) -> Callable: method.__module__ = self._cls.__module__ method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}" method.__doc__ = ( f"Method generated by attrs for class {self._cls.__qualname__}." ) return method def _add_method_dunders_safe(self, method: Callable) -> Callable: with contextlib.suppress(AttributeError): method.__module__ = self._cls.__module__ with contextlib.suppress(AttributeError): method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}" with contextlib.suppress(AttributeError): method.__doc__ = f"Method generated by attrs for class {self._cls.__qualname__}." return method

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.21338.366−704.166
Source linesThe number of non-empty source lines.614+245.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.045−6.068

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.615−20.739
Indentation frequencyHow rapidly indentation changes from line to line.614+20.5
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.614−13.669
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.613.894+8.171
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.0−0.804
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.92.966−0.272
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.069+0.269

Intercept 0.07 + feature contributions = -6.474 (log-odds).
Score = sigmoid(-6.474) = 0.002.

Score0.712
Score281
Run 1

The code is generally well-structured with clear class organization, logical method grouping, and consistent naming. It uses meaningful variable names, type hints, and docstrings that aid understanding. However, it has several readability challenges: high nesting in methods like _create_slots_class and add_setattr, long parameter lists, and complex conditionals that require careful reading. Some methods mix multiple responsibilities and the flow jumps between setup logic and conditional branches. The code is readable for experienced Python developers familiar with metaclasses but would be challenging for those without deep understanding of Python's class internals.

Run 2

The code is organized into a single large class with logical method separation, but several methods are excessively long (_create_slots_class, __init__, add_setattr) and contain deeply nested conditionals. Nesting reaches 3-4 levels with multiple boolean checks and loops, making control flow hard to follow. Intent is often unclear due to sparse comments that explain 'why' but not 'what' the complex conditional branches are doing. Code length is unnecessarily verbose - many methods could be extracted or simplified. Action granularity is mostly good with one operation per line, but some lines combine multiple comprehensions or conditional expressions. Reading flow is disrupted by heavy use of dunder methods, magic strings, and framework-specific patterns (closure cell manipulation, type reconstruction) that assume deep familiarity with Python internals and the attrs library. The __slots__ declaration, though long, does aid comprehension. Overall, the code demonstrates domain complexity but lacks refactoring into smaller, self-documenting units, and would benefit from clearer variable names and more explanatory comments for the metaclass machinery.

Run 3

The code shows significant readability issues: it's extremely long (700+ lines), has deeply nested methods (especially _create_slots_class with 6+ levels of indentation), and mixes multiple responsibilities within single methods. The _ClassBuilder class manages class construction, slot creation, method generation, and attribute handling simultaneously, making the logic tangled. Method names like _make_getstate_setstate and _add_method_dunders_unsafe are somewhat cryptic without deep attrs library context. The heavy use of private attributes (leading underscores) obscures the state management flow. While there are some good practices like docstrings, type hints, and comments explaining complex sections, the overall structure remains dense and difficult to follow. The action granularity is inconsistent - some lines pack multiple operations while others are appropriately separated. The caching property extraction logic, closure cell manipulation, and conditional branches create spaghetti-like flow that requires significant mental overhead to trace.

Run 1

Code Structure: Well-organized builder class with focused method-generation helpers, but initialization and slot creation combine many responsibilities. Nesting: Most methods are shallow; slot creation, closure updates, and setter hooks introduce several nested branches and loops. Clarity of intent: Descriptive method names communicate the overall purpose, but abbreviations such as cd, sa_attrs, and nval, extensive internal state, and undocumented metaprogramming details obscure implementation intent. Code length: Some complexity is justified, but duplicated initialization-generation methods, repeated metadata assignments, and excessive blank lines make the code longer than necessary. Action granularity: Most statements perform one action, although chained assignments and simultaneous assignment of multiple generated methods are denser. Reading flow: Consistent formatting and helper boundaries support navigation, while long conditions, numerous configuration flags, deferred script execution, and closure manipulation require substantial cross-referencing.

Run 2

Code Structure: Cohesive builder class with clearly separated method-generation and class-construction helpers, though initialization and slot creation handle many responsibilities. Nesting: Mostly moderate, but inheritance handling, closure updates, and setter hooks introduce deeper branches. Clarity of intent: Descriptive method names and state fields communicate the broad purpose; abbreviated locals, metaprogramming details, and absent explanatory comments obscure subtleties. Code length: Much complexity appears justified, but duplicated initialization-generation and metadata-setting logic, long methods, and excessive blank lines reduce concision. Action granularity: Generally one operation per line, with occasional chained or multi-target assignments that slightly increase reading effort. Reading flow: Consistent builder patterns and sequential processing help navigation, but numerous flags, deferred script execution, closures, and external helpers require readers to track substantial context.

Run 3

Code Structure: Cohesive builder class with well-separated method-generation operations, but initialization and slot creation combine many responsibilities. Nesting: Mostly moderate, with deeper loops, conditionals, and exception handling in closure updates and setter hooks. Clarity of intent: Descriptive method and field names communicate the overall purpose; missing explanatory comments/docstrings, abbreviated locals, and intricate metaprogramming obscure important details. Code length: Small helper methods are concise, but lengthy initialization and slot construction, duplicated init-generation logic, and excessive blank lines increase reading effort. Action granularity: Generally one action per line, with occasional chained assignments and multi-target unpacking adding density. Reading flow: The builder lifecycle and repeated attachment pattern are reasonably natural, but numerous state flags, external helpers, nested callbacks, and dynamic class modifications require substantial cross-referencing.