Paul's Python CoursePPC

Dataclasses

Not met yet

@dataclass above a class with typed fields writes __init__, __repr__ and __eq__ for you. Fields with defaults go after those without. @dataclass(frozen=True) makes the record read-only, and replace(card, to="York") makes a changed copy. A list default needs field(default_factory=list), for the same reason as the mutable default trap.

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks two dataclass objects with the same field values are not ==, as with a plain class.
  • Thinks a dataclass still needs __init__ written by hand.
  • Thinks frozen=True is only a note, and the fields can still be changed.
  • Thinks a frozen dataclass can't be used to make a changed copy with replace().
  • Thinks a dataclass field can default to a list like any other value.

Where it comes up