Basic Dataclass
Decorate a class with @dataclass and annotate fields. Python generates __init__, __repr__, and __eq__ automatically.
Python
from dataclasses import dataclass
# Without @dataclass (verbose)
class PersonManual:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
# With @dataclass (clean!)
@dataclass
class Person:
name: str
age: int
p = Person("Alice", 30)
print(p) # Person(name='Alice', age=30)
print(p.name) # Alice
print(Person("Bob", 25) == Person("Bob", 25)) # TrueβΆ Output
Person(name='Alice', age=30)
Alice
TrueDefault Values and field()
Use field() for mutable defaults (lists, dicts). Never use mutable defaults directly.
Python
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
grade: float = 0.0
courses: list = field(default_factory=list) # Correct!
# courses: list = [] β WRONG β shared across instances!
s1 = Student("Alice")
s2 = Student("Bob")
s1.courses.append("Python")
print(s1.courses) # ['Python']
print(s2.courses) # [] β independent list!βΆ Output
['Python']
[]__post_init__ β Computed Fields
Run code after __init__ for validation or computed attributes.
Python
from dataclasses import dataclass, field
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False) # Not a constructor param
def __post_init__(self):
if self.width <= 0 or self.height <= 0:
raise ValueError("Dimensions must be positive")
self.area = self.width * self.height
r = Rectangle(5, 3)
print(r) # Rectangle(width=5, height=3, area=15)
print(r.area) # 15βΆ Output
Rectangle(width=5, height=3, area=15)
15Ad β 336Γ280
Frozen Dataclasses β Immutable Objects
frozen=True makes all fields read-only and the object hashable (usable as dict key).
Python
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(3.0, 4.0)
print(p) # Point(x=3.0, y=4.0)
try:
p.x = 10 # AttributeError!
except Exception as e:
print(e)
# Hashable β can be dict key or set member
locations = {p: "Home"}
print(locations[Point(3.0, 4.0)]) # HomeβΆ Output
Point(x=3.0, y=4.0)
cannot assign to field 'x'
Home