Dataclasses
@dataclass turns a class with type-annotated fields into a full data container: Python writes __init__, __repr__ and __eq__ for you. Use it whenever a class mainly holds data, such as a product, an order or a config. Options like frozen=True and order=True add immutability and sorting.
Before and after
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
mug = Product("mug", 8.5, 3)
print(mug)
print(mug.price * mug.quantity)
print(mug == Product("mug", 8.5, 3))Product(name='mug', price=8.5, quantity=3) 25.5 True
Those few lines give you a constructor, a readable print-out and value comparison. Written by hand, the same class takes around 15 lines.
Mutable defaults: default_factory
from dataclasses import dataclass, field
@dataclass
class Order:
customer: str
items: list[str] = field(default_factory=list)
a = Order("Ana")
b = Order("Ben")
a.items.append("tea")
print(a)
print(b)Order(customer='Ana', items=['tea']) Order(customer='Ben', items=[])
Methods and computed values
from dataclasses import dataclass
@dataclass
class Rectangle:
width: float
height: float
@property
def area(self) -> float:
return self.width * self.height
def scaled(self, factor: float) -> "Rectangle":
return Rectangle(self.width * factor, self.height * factor)
r = Rectangle(2, 3)
print(r.area)
print(r.scaled(2))6 Rectangle(width=4, height=6)
frozen and order
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
versions = [Version(3, 15), Version(3, 9), Version(2, 7)]
print(sorted(versions))
print(max(versions))
try:
versions[0].major = 4
except FrozenInstanceError:
print("Can't change a frozen dataclass")[Version(major=2, minor=7), Version(major=3, minor=9), Version(major=3, minor=15)] Version(major=3, minor=15) Can't change a frozen dataclass
order=True compares fields in order, like tuples. frozen=True makes objects read-only, so they're safe to share and can be used as dictionary keys.
Converting to dictionaries
from dataclasses import dataclass, asdict
import json
@dataclass(slots=True)
class User:
name: str
email: str
active: bool = True
user = User("Ana", "ana@example.com")
print(asdict(user))
print(json.dumps(asdict(user))){'name': 'Ana', 'email': 'ana@example.com', 'active': True}
{"name": "Ana", "email": "ana@example.com", "active": true}asdict() is the quick route to JSON. slots=True makes objects smaller and a little faster, and stops typos like user.emial = ... from silently creating new attributes.
Practice
Create a dataclass Book with title: str, pages: int and read: bool = False. Make a list of three books — Book("Dune", 412), Book("Atomic Habits", 320, True), Book("SPQR", 608) — then print the titles of unread books and, on a second line, their total pages.
['Dune', 'SPQR'] 1020