Code

Dataclasses: Less Typing

Many classes are mostly data: a quest has a title, a reward, some tags. Writing __init__, __repr__ and __eq__ for each one gets old fast. The @dataclass decorator writes them for you from a list of annotated fields:

from dataclasses import dataclass, field

@dataclass
class Bridge:
    start: str
    end: str
    length: int = 10                   # default value
    planks: list = field(default_factory=list)

b = Bridge("Mossreach", "Ashfall")
print(b)   # Bridge(start='Mossreach', end='Ashfall', length=10, planks=[])
print(b == Bridge("Mossreach", "Ashfall"))   # True

Rules worth remembering:

  • Every field needs a type annotation (name: type).
  • Fields with defaults must come after fields without.
  • Never write planks: list = []. Mutable defaults need field(default_factory=list) so every object gets a fresh list (dataclasses even raise an error if you forget).
  • You can still add your own methods.

Assignment

Turn Quest into a dataclass with these fields, in this order:

  1. title: str (no default)
  2. reward: int, default 10
  3. tags: list, default a new empty list
  4. done: bool, default False

Then finish complete(): set done to True and return the reward.