Python · Module 5 · Lesson 51 min read

Dataclasses

Less boilerplate for data-holding classes

@dataclass writes __init__, __repr__ and __eq__ for you from type-annotated fields:

Python
from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float
    qty: int = 0

Useful options

  • @dataclass(frozen=True) makes objects immutable (and hashable, so they can be dict keys).
  • @dataclass(order=True) adds <, > so objects can be sorted.
  • field(default_factory=list) is the safe way to give a list/dict default (never tags: list = []).
  • __post_init__ runs after __init__, which is handy for validation.

When to use

Whenever a class is mainly data: products, users, settings, API responses. Use a normal class when behaviour matters more than data.

▶️ Runs in the app.

Example

Python
from dataclasses import dataclass, field

@dataclass
class Product:
    name: str
    price: float
    qty: int = 0
    tags: list[str] = field(default_factory=list)

    def __post_init__(self):
        if self.price < 0:
            raise ValueError("price must be >= 0")

    @property
    def total(self):
        return self.price * self.qty

p = Product("Pen", 2.5, qty=4)
print(p)              # Product(name='Pen', price=2.5, qty=4, tags=[])
print(p.total)        # 10.0
print(p == Product("Pen", 2.5, 4))   # True

@dataclass(frozen=True, order=True)
class Point:
    x: int
    y: int

print(sorted([Point(2, 1), Point(1, 5)]))   # [Point(x=1, y=5), Point(x=2, y=1)]