After this lesson you can write a data-holding class in a few lines instead of a few dozen.
The boilerplate problem
Many classes exist only to hold a few values together. A hand-written version needs __init__, a __repr__ so it prints sensibly, and __eq__ so two equal records compare equal. For a product that is about fifteen lines, and all of it is repetitive:
class ProductPlain:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def __repr__(self):
return f"ProductPlain(name={self.name!r}, price={self.price!r}, stock={self.stock!r})"
def __eq__(self, other):
return (self.name, self.price, self.stock) == (other.name, other.price, other.stock)
print(ProductPlain("Pen", 2.5, 40))ProductPlain(name='Pen', price=2.5, stock=40)The same class as a dataclass
The dataclasses module in the standard library writes all of that from a list of fields. You name each field with an annotation (a colon and a type) in the class body, and add the @dataclass decorator:
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
stock: int
pen = Product("Pen", 2.5, 40)
print(pen)
print(pen == Product("Pen", 2.5, 40))
print(pen.name, pen.price)Product(name='Pen', price=2.5, stock=40)
True
Pen 2.5You get __init__, a readable __repr__ and a content-based __eq__ for free. The annotations are what tell the decorator which fields exist. Python does not check the types at run time. They are there for readers and for tools.
Defaults and default_factory
Fields can have defaults. Fields with defaults must come after those without, just like function parameters:
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
stock: int = 0
tags: list = field(default_factory=list)
mug = Product("Mug", 6.0)
lamp = Product("Lamp", 18.0, 12)
mug.tags.append("kitchen")
print(mug)
print(lamp)Product(name='Mug', price=6.0, stock=0, tags=['kitchen'])
Product(name='Lamp', price=18.0, stock=12, tags=[])For a list, dictionary or set default, use field(default_factory=list), which builds a fresh list per object. This avoids the shared list problem from the attributes lesson. If you try tags: list = [], Python stops you:
@dataclass
class Bad:
tags: list = []ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factoryFrozen and ordered dataclasses
Two options are worth knowing. frozen=True makes objects read-only, and order=True adds <, >, <= and >=, comparing fields in the order they are written:
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
older = Version(1, 4)
newer = Version(2, 0)
print(older < newer)
print(sorted([newer, older]))
try:
older.major = 9
except Exception as error:
print(type(error).__name__)True
[Version(major=1, minor=4), Version(major=2, minor=0)]
FrozenInstanceErrorThe error type is FrozenInstanceError. A frozen dataclass is a good way to represent a value that should not change after it is created.
Checking values with __post_init__
The generated __init__ does not validate anything. If you need that, or a calculated field, define __post_init__, which runs straight after:
@dataclass
class Order:
item: str
quantity: int
unit_price: float
total: float = 0.0
def __post_init__(self):
if self.quantity <= 0:
raise ValueError("quantity must be positive")
self.total = self.quantity * self.unit_price
print(Order("Pen", 4, 2.5))Order(item='Pen', quantity=4, unit_price=2.5, total=10.0)Turning one into a dictionary
asdict converts a dataclass into a plain dictionary, which is a convenient step towards JSON:
from dataclasses import asdict
import json
print(asdict(Product("Pen", 2.5, 40)))
print(json.dumps(asdict(Version(1, 4)))){'name': 'Pen', 'price': 2.5, 'stock': 40, 'tags': []}
{"major": 1, "minor": 4}Newer Python versions add more options, such as slots and keyword-only fields. Those are not covered here because the examples in this tutorial run on Python 3.9.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Forgetting the annotation.
name = ""without a colon and type is a class attribute, not a field. - Using a list or dictionary as a default. Use
field(default_factory=...). - Putting a field without a default after one with a default. Python raises a
TypeError. - Expecting type checking.
Product("Pen", "free", "lots")is accepted. Validate in__post_init__if it matters. - Mutating a frozen object. Create a new one instead, for example with
dataclasses.replace.
Exercise
Write a dataclass Book with title: str, author: str and pages: int = 100, plus a list field reviews that defaults to an empty list. Create a book, append one review string, and print the book.
Show one possible answer
from dataclasses import dataclass, field
@dataclass
class Book:
title: str
author: str
pages: int = 100
reviews: list = field(default_factory=list)
book = Book("Night Trains", "A. Writer")
book.reviews.append("Short and sharp")
print(book)Book(title='Night Trains', author='A. Writer', pages=100, reviews=['Short and sharp'])Key points
- @dataclass generates __init__, __repr__ and __eq__ from the annotated fields in the class body.
- Fields can have defaults, but mutable defaults like lists must use field(default_factory=list).
- frozen=True makes objects read-only, and order=True adds comparison methods so they can be sorted.
- __post_init__ runs after the generated __init__ and is the place for validation or derived fields.
- dataclasses.asdict() turns an object into a dictionary, which is handy for JSON.