What are Python Data Classes?
Introduced in Python 3.7, the
@dataclass decorator automates the creation of boilerplate code for classes that primarily exist to store data. It automatically generates __init__, __repr__, __eq__, and other useful methods based on your type hints!python
Default Values and Factories
Like regular functions, you can provide default values for attributes.
python
Post-Initialization Logic: __post_init__
Sometimes you need to perform additional setup or validation after the
__init__ has run.python
Immutable Data Classes: frozen=True
If you want your object to be immutable (read-only), you can "freeze" it. This also makes the object hashable, meaning you can use it as a key in a dictionary.
python
Memory Optimization: slots=True (Python 3.10+)
By default, Python objects use a dictionary (
__dict__) to store their attributes, which can use a lot of memory. Creating a class with slots tells Python to use a fixed, efficient space for attributes.python
Converting to Dict and Tuple
The
dataclasses module provides helper functions to convert your objects to other Python types (useful for JSON serialization).python
Summary
| Feature | Syntax | Purpose |
|---|---|---|
| Decorator | @dataclass | Automate boilerplate methods |
| Defaults | attr: int = 0 | Initial values |
| Factory | field(default_factory=f) | Defaults for mutable items |
| Post-Init | def __post_init__(self): | Setup after init |
| Immutable | frozen=True | Make read-only and hashable |
| Optimize | slots=True (3.10+) | Minimize memory usage |
| Best For | Record-like objects, Configs, DTOs | |
| asdict() | asdict(obj) | Convert to dictionary |
| astuple() | astuple(obj) | Convert to tuple |