How do dataclasses simplify class definitions in Python?
· Category: Python Programming
Short answer
The dataclasses module (Python 3.7+) automatically generates __init__, __repr__, __eq__, and other special methods based on class annotations, reducing boilerplate for data-centric classes.
Steps
- Import
@dataclassfromdataclasses. - Annotate fields with type hints.
- Customize behavior with parameters like
frozen=True,order=True, ordefault_factory.
from dataclasses import dataclass, field
from typing import List
@dataclass
class Product:
name: str
price: float
tags: List[str] = field(default_factory=list)
p = Product("Laptop", 999.99)
p.tags.append("electronics")
print(p)
Tips
- Use
frozen=Trueto create immutable dataclasses (similar to named tuples but more flexible). field()allows per-field defaults, metadata, and comparison control.__post_init__runs after the generated__init__for custom validation.dataclasses.asdict()converts instances to dictionaries.
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(1.0, 2.0)
# p.x = 3.0 # FrozenInstanceError
Common issues
- Mutable default values (like
[]) must usedefault_factory=list, notdefault=[]. - Type hints are required for dataclass fields, even if you do not use static type checking.
- Inheritance with dataclasses requires care with field ordering and defaults.