01
Overview
dataclass auto-generates __init__, __repr__, __eq__. Use @dataclass decorator. Fields with type hints. frozen=True for immutability. Default values, default_factory for mutable defaults. Slots for memory efficiency.
bash
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Point:
x: float
y: float
@dataclass
class Config:
host: str = "localhost"
port: int = 8080
tags: list = field(default_factory=list)
p=Point(1,2)
print(p) # Point(x=1, y=2)02
Best Practices
Use @dataclass for data containers. frozen=True for immutable. default_factory for mutable defaults. Use slots=True (3.10+) for memory. Inherit with care (field ordering). Use asdict/astuple for conversion. Combine with type hints.)
Ready to try Dataclasses?
Visit the official site for the latest version and full documentation.
Visit Dataclasses