Structural pattern matching in Python
match/case: branching on the shape of data, not just its value.
def describe(command):
match command.split():
case ["go", direction]:
return f"walking {direction}"
case ["look"]:
return "you see a wall of code"
case ["take", *items]:
return f"picked up {len(items)} items"
case _:
return "unknown command"
print(describe("go north"))
print(describe("take sword shield"))
How it works
- Each
casetries to fit the split command list. - Patterns capture parts into names like
direction. *itemsmatches a variable-length tail.case _is the catch-all fallback.
Keywords and builtins used here
_casedefdescribelenmatchprintreturn
The run, in numbers
- Lines
- 14
- Characters to type
- 308
- Tokens
- 88
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 59 seconds.
Step 4 of 7 in Flow control, step 19 of 72 in Language basics.