Python course / Advanced
Dataclasses and the data model
Let a dataclass write the boilerplate, and learn the methods Python calls on your behalf. A changeable object used as a dictionary key disappears from the dictionary the moment you change it.
- fields
- default_factory
- __post_init__
- frozen and replace
- ordering
- hashing
- __call__
- descriptors
Runs in your browser. Start straight away; create an account when you want your progress kept.
from dataclasses import dataclass, replace
@dataclass(frozen=True, order=True)
class Item:
name: str
pence: int
tags: tuple[str, ...] = ()
def __post_init__(self):
if self.pence < 0:
raise ValueError("pence cannot be negative")
tea = Item("tea", 350, ("hot",))
cheaper = replace(tea, pence=300)
print(tea)
print(cheaper)
print("sorted:", sorted([tea, cheaper])[0].pence)
Item(name='tea', pence=350, tags=('hot',))
Item(name='tea', pence=300, tags=('hot',))
sorted: 300
What you will learn
- Replace hand-written __init__, __repr__ and __eq__ with a dataclass, and know where it gets them from.
- Give a dataclass field a list or dictionary default safely, with field(default_factory=...).
- Validate fields and fill in derived ones after a dataclass's generated __init__ has run.
- Make a dataclass that cannot be changed after creation, and make changed copies of it instead.
- Choose between a dataclass, a NamedTuple, a TypedDict and a plain class by what the data has to do.
- Write a descriptor that controls an attribute on every class that uses it, and see property and methods as descriptors.
The lessons in this module
- What @dataclass writes for you
- Defaults that are lists
- __post_init__: checking and working things out
- frozen dataclasses and replace
- Equality, hashing and dataclasses
- Ordering dataclasses
- Dataclasses to JSON and back
- Which shape for your data
- Field order, defaults and kw_only
- slots: catching the misspelt attribute
- Objects you can call
- __getattr__: answering for missing attributes
- __setattr__: a rule for every assignment
- Descriptors: how property works
- __init_subclass__: classes that register themselves
- __format__: your objects in f-strings
- The hash that changed
- When the magic is the problem
- Capstone: one more field
- Module review: the price list editor
Ready when you are
Previous: Context managers. Next: functools and itertools. All modules are on the course page.