Lesson 10 · Core
Pattern matching
match (Python 3.10+) looks like switch, but it matches shapes: types, list lengths, dict keys and object fields. It can bind variables as it matches.
- There's no fall-through and no
break. The first matching case wins. case _:is the default.case int():matches by type, andcase [x, y]:matches a 2-item sequence and binds both items.case {"type": "click", "x": x}:matches dicts that contain those keys.case Point(x=0, y=y):matches objects by their attributes.- A guard adds an extra condition:
case [x, y] if x == y:
Branch on a command
match command.split():
case ["go", direction]:
move(direction)
case ["quit" | "exit"]:
stop()
case _:
print("unknown")Experiment
def handle(event):
match event:
case {"type": "click", "x": x, "y": y}:
return f"click at {x},{y}"
case {"type": "key", "key": "q" | "Q"}:
return "quit"
case {"type": "key", "key": k}:
return f"key {k}"
case [x, y] if x == y:
return "a pair of equals"
case _:
return "ignored"
for e in [{"type": "click", "x": 1, "y": 2}, {"type": "key", "key": "Q"},
{"type": "key", "key": "a"}, [3, 3], "noise"]:
print(handle(e))Exercise 27: Describe a value
Use a match statement:
None | "nothing" |
an int, e.g. 5 | "number 5" |
a str, e.g. "hi" | "text 'hi'" |
[] | "empty list" |
[7] | "one item: 7" |
[1, 2, 3] | "list starting with 1" |
| anything else | "something else" |