Module lessons (2/4)
dataclass: data classes without boilerplate
@dataclass, field(default_factory=...), frozen=True, and generated __init__/__repr__/__eq__.
What you'll learn in this lesson
- Eliminate the repetitive boilerplate of
__init__,__repr__and__eq__with the@dataclassdecorator. - Configure fields with securely mutable defaults via
field(default_factory=list). - Create immutable and hashable value-objects using
@dataclass(frozen=True). - Validate or calculate derived fields immediately after initialization with
__post_init__.
Overview
When you write a class that is primarily used to hold structured data, repeating __init__, __repr__, and __eq__ by hand makes the code cumbersome and introduces distracting errors. The standard module dataclasses reads the type annotations of the class and automatically generates these dunder methods for you.
Unlike namedtuple (which is always immutable and derives from tuple), @dataclass generates real Python classes that you can extend with custom methods, optional fields, and selective immutability.
Sections covered in this lesson
- 11. Complete data class in a few lines
- 22. Safe mutable defaults with
field(default_factory=...) - 33. Immutable and hashable objects with
frozen=True - 44. Validation and derived fields in
__post_init__ - 5Check for understanding
- 6Test yourself
Unlock "dataclass: data classes without boilerplate" and the full Python Course curriculum
@dataclass, field(default_factory=...), frozen=True, and generated __init__/__repr__/__eq__.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.