Ad – 728Γ—90
πŸš€ Advanced Python

Python Dataclasses – Clean Data Container Classes

Dataclasses (Python 3.7+) automatically generate boilerplate methods (__init__, __repr__, __eq__) based on type-annotated class variables. They dramatically reduce the code needed to create data-holding classes while maintaining all the power of regular classes.

⏱️ 18 min read🎯 AdvancedπŸ“… Updated 2026

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 True

Default 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) 15
Ad – 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