Sub topic 11
Annotating classes and dataclasses
This chapter assumes you can write Python classes, know the name: type syntax for variables and parameters, and have run mypy or pyright on a file.
Annotating instance attributes
A static checker infers an instance attribute's type from the first assignment in __init__. Annotate the __init__ parameters, and the attributes usually get the right types without further work. Always write -> None on __init__ so the checker treats the method as annotated.
from typing import ClassVar
class Account:
interest_rate: ClassVar[float] = 0.02
def __init__(self, owner: str, balance: float = 0.0) -> None:
self.owner = owner
self.balance = balance
def deposit(self, amount: float) -> None:
self.balance += amount
account = Account("Ada")
account.deposit(50)
print(account.balance)self needs no annotation. The checker already knows its type.
ClassVar[float] marks interest_rate as a class-level attribute shared by all instances. A checker reports an error if code assigns to it through an instance, such as account.interest_rate = 0.05.
You can also declare an attribute in the class body without a value, for example owner: str. This is useful when the attribute is set somewhere other than __init__.
Annotating dataclasses
A dataclass (a class decorated with @dataclass) uses class-body annotations as its field list. The annotations are required, because the decorator reads them to generate __init__, __repr__, and __eq__.
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: int
items: list[str] = field(default_factory=list)
note: str | None = None
order = Order(1)
order.items.append("book")
print(order)This prints Order(order_id=1, items=['book'], note=None).
Fields without defaults must come before fields with defaults. A checker also verifies the generated constructor, so Order("x") is reported as an error even though the call would run.
Two other tools matter in dataclasses:
ClassVarfields are excluded from the generated__init__.@dataclass(frozen=True)makes instances read-only, and checkers report attribute assignment as an error.
Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| Checker reports an attribute is possibly `None` | Attribute annotated `X \ | None` | Narrow with `is not None` before use |
| `ValueError: mutable default` | `[]` or `{}` as a dataclass default | Use `default_factory` | |
| Checker reports an assignment to a class variable through an instance | Attribute declared `ClassVar` | Assign through the class | |
| `TypeError: non-default argument follows default argument` | Field order in a dataclass | Put required fields first |
Annotations on a plain class are not enforced at runtime. A dataclass does not validate its fields either. Order("x") constructs happily, and only the static checker complains.
A method that returns an instance of its own class needs a forward reference, which a later chapter covers.
Exercise
Write a dataclass Config with a required name: str, a tags: list[str] that defaults to an empty list, and a timeout: float that defaults to 30.0. Where must name appear, and why?
Show answer
@dataclass
class Config:
name: str
tags: list[str] = field(defaultfactory=list)
timeout: float = 30.0
name must come first because dataclass fields without defaults cannot follow fields with defaults. tags uses `defaultfactory` so each instance gets its own list.