Dataclasses

typed records with generated __init__, __repr__ and __eq__

25 min · interactive lesson with runnable code and 5 graded exercises.

What you'll be able to do

  • Define a dataclass with defaults
  • Use field(default_factory=list) for mutable defaults
  • Make records immutable with frozen=True
  • Validate in __post_init__ and convert with asdict

The full lesson is free with an account.

A basic dataclass

Defaults & default_factory

frozen=True

Equality

__post_init__ and asdict

dataclass vs NamedTuple vs TypedDict

Common pitfalls