▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Dataclasses
Less boilerplate for classes that mostly hold data.
🎬 Video version coming soon — read it now
Many classes mostly hold data: a product, a student record, a coordinate. Writing __init__, __repr__ and __eq__ for each one is repetitive. Dataclasses write them for you.
From those four lines Python generates __init__, a helpful __repr__ and __eq__.
The parts
@dataclassis a decorator that adds the generated methods. You'll learn to write decorators in the Advanced Python Features course.name: stris a type hint. It documents the expected type; Python doesn't enforce it at runtime.- Fields with defaults must come after fields without, just like function parameters.
Adding methods
A dataclass is still a normal class:
Lists as defaults
field(default_factory=list) gives every student a new empty list. Python won't even let you write skills: list = [], which protects you from the shared-default bug.
Frozen dataclasses
Frozen objects are safe to use as dictionary keys and in sets.
Sorting
order=True compares objects field by field, in the order they're defined.
In one line
@dataclass writes __init__, __repr__ and __eq__ for data-holding classes, with options for defaults, freezing and sorting.
Share with a friend