match statements

match (Python 3.10+) compares a value against patterns, top to bottom, and runs the first case that fits. It is more than a switch:

  • A literal like case 0: or case "quit": matches that value.
  • A bare name like case other: matches anything and binds it. case _: is the catch-all.
  • case [x, y]: matches a sequence of length two and binds both items. case [first, *rest]: takes any length of one or more.
  • case {"type": "click", "x": x}: matches a dict that has those keys.
  • if after a pattern adds a guard.

A common bug: case limit: doesn't compare with a variable named limit. It captures anything into a new name. Use a dotted name, like Color.RED, or a guard.

Run it, then add a case for ["undo"].