Dataclass¶

Dataclass is a decorator (we'll talk about decorators in more detail later) that automatically creates init(), repr(), and eq() methods. It's designed for creating classes whose main purpose is data storage. Type annotations are mandatory.

There is a more advanced alternative called attrs, but Glyph Lefkowitz updated his 2016 article "The One Python Library Everyone Needs" with a note that over the years, dataclass has become significantly more advanced (largely due to attrs' influence) and now it's quite possible to get by without attrs by simply using dataclass.

In [3]:
from dataclasses import dataclass
from decimal import *
from datetime import datetime

@dataclass
class Transaction:
    value: Decimal
    issuer: str = 'Default Bank'
    dt: datetime = datetime.now()

t1 = Transaction(value=1000_000, issuer='Deutsche Bank', dt = datetime(2025, 1, 1, 12))
t2 = Transaction(1000)

print(t1)
print(t2)
Transaction(value=1000000, issuer='Deutsche Bank', dt=datetime.datetime(2025, 1, 1, 12, 0))
Transaction(value=1000, issuer='Default Bank', dt=datetime.datetime(2025, 6, 5, 13, 35, 57, 183323))

A dataclass can be made immutable using the frozen=True directive.

In [1]:
from dataclasses import dataclass

@dataclass(frozen=True)
class User:
    name: str
    account: int