Dataclasses

Writing __init__, __repr__ and __eq__ by hand gets old. @dataclass writes them from type-annotated fields.

  • Fields with defaults go after fields without.
  • A list default must be field(default_factory=list). A plain = [] would be shared by every instance, so dataclasses refuse it with a ValueError.
  • frozen=True makes instances read-only, and therefore hashable. Use it for values like points and keys.
  • order=True adds < and friends, comparing fields in order like a tuple.

Dataclasses are the quickest way to model data in an interview, and they keep your code short enough to talk through. slots=True also exists: see the __slots__ page.

Run it, then try items: list[str] = [] and read the error.