Python OOP
Python Dataclasses
The @dataclass decorator automatically writes common boilerplate methods like __init__, __repr__ and __eq__ for classes that mainly just hold data.
Why Dataclasses?
Many classes exist purely to store a group of related values. Writing __init__ and __repr__ by hand for these is repetitive; the dataclasses module removes that boilerplate.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 1
p = Product("Notebook", 45.5)
print(p)Product(name='Notebook', price=45.5, quantity=1)@dataclass automatically generates __init__ (using the type-annotated fields), a readable __repr__ for printing, and __eq__ for comparing two instances field by field.
default_factory for Mutable Defaults
You cannot give a field a mutable default like [] directly. Instead, use field(default_factory=list) to safely create a fresh list or dictionary for each new object.
from dataclasses import dataclass, field
@dataclass
class Cart:
items: list = field(default_factory=list)
c1 = Cart()
c1.items.append("Pen")
c2 = Cart()
print(c1.items, c2.items)['Pen'] []Frozen (Immutable) Dataclasses
Passing frozen=True makes instances immutable — once created, their fields cannot be reassigned, which is useful for representing fixed values safely.
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
p.x = 5dataclasses.FrozenInstanceError: cannot assign to field 'x'Reach for @dataclass whenever a class is mostly about storing structured data with little custom behaviour — it keeps your code short and consistent.
| Feature | How |
|---|---|
| Auto __init__/__repr__/__eq__ | @dataclass on the class |
| Default value | field_name: type = value |
| Safe mutable default | field(default_factory=list) |
| Immutability | @dataclass(frozen=True) |
