Repository navigation
Description
Accessing dataclass fields through the class itself seems idiosyncratic and should arguably be disallowed by type checkers. Depending on how a field is defined, such access can produce inconsistent or even unsound behavior:
from dataclasses import dataclass, field
@dataclass
class Unslotted:
attr: int = 0
@dataclass(slots=True)
class Slotted:
attr: int = 0
@dataclass
class Factory:
attr: list[int] = field(default_factory=list)
Unslotted.attr # Returns the default value.
Slotted.attr # Returns a member descriptor, not an int.
Factory.attr # AttributeError at runtime.
Unslotted.attr = 123 # Does not change the constructor default.
Slotted.attr = 123 # Breaks the slot descriptor and instantiation.
Factory.attr = [123] # Does not change the default factory.When testing this snippet in multiplay, the only diagnostics reported are:
ty v0.0.115: rejectsSlotted.attr = 123.mypy v2.4.1: rejects bothSlotted.attrandSlotted.attr = 123.pyright v1.1.414,pyrefly v1.5.1, andzuban v0.11.1report no errors.
Proposal
Treat dataclass fields as instance-only attributes for static typing purposes, rejecting both reads and assignments through the class itself.
That is, with respect to attribute access,
@dataclass
class Foo:
attr: int = 0should be treated like
class Foo:
def __init__(self, attr: int = 0) -> None:
self.attr: int = attrAlthough dataclasses retain default values as class attributes under certain circumstances, this runtime behavior need not be reflected in the static interface.
In particular, switching between default and default_factory or enabling slots=True should arguably not affect whether a field is accessible through the class itself.
There is already precedent for this interpretation in the typing specification:
A
Finaldataclass field initialized in the class body is not a class attribute unless explicitly annotated withClassVar.
The proposal would generalize this interpretation to ordinary dataclass fields.
Explicitly descriptor-typed fields may warrant separate consideration.
Related discussions
- Conformance suite: Questionable tests in dataclasses_descriptors.py #2259
- https://discuss.python.org/t/possible-modification-to-classvar/47268
- https://discuss.python.org/t/treatment-of-final-attributes-in-dataclass-likes/47154
- https://discuss.python.org/t/typing-spec-gap-about-properties-in-protocols/87243
Activity