@dataclass writes the methods¶
Level: 201 → 301 · for Python programmers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
One line: @dataclass reads the class's annotations and writes __init__, __repr__ and __eq__ for you, and nothing else unless asked — no ordering without order=True, no hash unless frozen, no __slots__ without slots=True, no type check ever — while it refuses a mutable default and accepts a mutable field without a word.
What the finished page has to answer¶
- What was written, shown with
inspect.signature(C.__init__)andvars(C)before and after; and the rule that a field without a default cannot follow one with, which isTypeErrorat class creation. field():default_factory,init=False,repr=False,compare=False,kw_only=True;__post_init__for the derived field.frozen=True: assignment raisesFrozenInstanceError, a subclass ofAttributeError, and the hash comes back, which Defining__eq__deletes__hash__section 6 measures.order=Truecompares field tuples in declaration order, and refuses to coexist with a hand-written__lt__.slots=True(3.10) and what it changes about A class attribute is shared section 6.asdictandastuplecopy deeply,replacemakes a new instance, andfields()is the list the decorator worked from, which is why an unannotated name is not in it.- Types are not checked, ever:
C('a')when the field saysintruns, which is Annotations are not checked from the class's side.
See also¶
- Defining
__eq__deletes__hash__, A class attribute is shared and A default is computed once: three pages that each measure one of the decorator's decisions dataclasses↗ in the Python docs, and PEP 557 ↗- Representing a record ↗ in the Rust library, where
#[derive]writes the same methods and the compiler checks the types the decorator here never does