Sub topic 11
Annotating classes and dataclasses
This chapter assumes you can write Python classes, you know basic annotations such as int, str | None, and list[str], and you can run a checker such as mypy or pyright. Here you will see how annotations describe the attributes and methods of a class, and how dataclasses turns those annotations into working code.
Annotating a regular class
In a regular class, you annotate methods the way you annotate functions. Two details are specific to classes.
selfandclsneed no annotation. The checker infers them as the enclosing class.__init__is annotated-> None. Mypy treats an__init__with no annotations at all as untyped and skips its body unless you pass--check-untyped-defs. Writing-> Nonemakes the checker examine the body.
class Account:
interest_rate: float = 0.02
def __init__(self, owner: str, balance: float = 0.0) -> None:
self.owner = owner
self.balance = balance
self.history: list[float] = []
def deposit(self, amount: float) -> None:
self.balance += amount
self.history.append(amount)
def total(self) -> float:
return self.balance
acct = Account("Ada")
acct.deposit(25.0)
print(acct.total(), acct.history)The checker infers self.owner as str and self.balance as float from the parameters, so you do not repeat them. The attribute self.history starts as an empty list, which gives the checker nothing to infer from. The annotation self.history: list[float] fixes that. Annotate an attribute once, at the place where it is first assigned. If you annotate it again elsewhere, mypy reports a redefinition error.
Class variables and instance variables
An annotation in the class body, such as interest_rate: float = 0.02, is ambiguous to a checker. It could be a default for each instance or a value shared by the whole class. Checkers treat it as an attribute that instances may override. To mark a value as belonging to the class only, use ClassVar.
from typing import ClassVar
class Counter:
instances: ClassVar[int] = 0
def __init__(self) -> None:
Counter.instances += 1
self.id: int = Counter.instances
a = Counter()
b = Counter()
print(Counter.instances, a.id, b.id)A checker rejects an assignment such as a.instances = 5, because instances is a ClassVar. At runtime Python would allow it and create an instance attribute that shadows the class one.
| Where the attribute is declared | Meaning to the checker |
|---|---|
| `self.x: int = ...` in `__init__` | Instance attribute |
| `x: int = ...` in the class body | Attribute with a class-level default, which instances may override |
| `x: ClassVar[int] = ...` in the class body | Class attribute, not assignable through an instance |
Dataclasses
A dataclass reads the annotations in the class body and generates __init__, __repr__, and __eq__ from them. Here the annotations have a runtime effect. They decide which names become fields. Their types are still not checked.
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: int
items: list[str] = field(default_factory=list)
note: str | None = None
total: float = 0.0
order = Order(1, ["pen"])
print(order)
print(Order(2) == Order(2))The output is Order(order_id=1, items=['pen'], note=None, total=0.0) followed by True.
Three rules matter in practice.
- Only annotated names become fields. Writing
tax = 0.2without an annotation creates a plain class attribute and does not add an__init__parameter. - Mutable defaults need
default_factory. Writingitems: list[str] = []raisesValueErrorwhen the class is defined. Dataclasses refuse it because every instance would share one list. Usefield(default_factory=list)so each instance gets a new list. - Fields without defaults must come before fields with defaults. Otherwise the generated
__init__would have a required parameter after an optional one, and Python raisesTypeErrorwhen the class is defined.
The next example shows the first and third rules together.
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float = 1.0
tax = 0.2 # no annotation, so this is not a field
print(Item("pen")) # Item(name='pen', price=1.0)
print(Item.tax) # 0.2Excluding and freezing fields
ClassVar works in dataclasses too, and dataclasses skip any ClassVar annotation when they build fields. The frozen=True option makes instances read-only. A checker flags assignment to a frozen field, and Python raises FrozenInstanceError at runtime.
from dataclasses import FrozenInstanceError, dataclass
from typing import ClassVar
@dataclass(frozen=True)
class Point:
x: float
y: float
dimensions: ClassVar[int] = 2
def shifted(self, dx: float, dy: float) -> "Point":
return Point(self.x + dx, self.y + dy)
@classmethod
def origin(cls) -> "Point":
return cls(0.0, 0.0)
p = Point(1, 2)
print(p.shifted(1, 1))
print(Point.origin())
try:
p.x = 5 # type: ignore[misc]
except FrozenInstanceError:
print("frozen")The # type: ignore[misc] comment keeps the checker quiet about the deliberate error so the example runs cleanly. Without it, the checker reports the assignment, which is the behavior you want in real code.
The quotes around "Point" are needed because the class name does not exist yet while its own body is running. Forward references and postponed evaluation get their own chapter, so for now just quote a class's own name inside its body. Python 3.11 and later also offers typing.Self, which you can use as the return type of a method that returns an instance of the same class.
How a dataclass field is decided
Common errors
- Attribute set outside
__init__. If a method createsself.cache = {}and__init__never declares it, some checkers report that the attribute is missing or has an unknown type. Declare every attribute in__init__or in the class body. - Changing an attribute's type later. If
self.balancewas inferred asfloat, thenself.balance = "n/a"is an error. Declare the attribute asfloat | Nonewhen it can legitimately holdNone. - Expecting dataclasses to validate.
Order("x")runs without error even thoughorder_idis annotatedint. Dataclasses add no runtime checks, so a checker is the only tool that catches this. - Subclass field order. A subclass of a dataclass appends its fields after the parent's. A required field in the child after a defaulted field in the parent raises the same
TypeErroras above.
Exercise
A dataclass declares tags: list[str] = []. What happens when Python defines the class, and how do you fix it? Also, why does Order("x") run without error when order_id is annotated int?
Show answer
Python raises ValueError because a mutable default would be shared by every instance. Fix it with tags: list[str] = field(default_factory=list). Order("x") runs because dataclasses use annotations to build the fields but never check the types of the values passed in. Only a static checker such as mypy or pyright reports that "x" is not an int.
Exercise
You write rate = 0.05 inside a dataclass body (no annotation) and limit: ClassVar[int] = 10. Which of these become __init__ parameters?
Show answer
Neither. rate has no annotation, so it is a plain class attribute. limit is annotated with ClassVar, so dataclasses skip it. Only annotated names that are not ClassVar become fields and __init__ parameters.