JSON events and exhaustive matching
Mapping patterns for JSON shaped like LLM events, then assert_never (3.11) on a union of classes. The last call reaches assert_never on purpose.
match can take apart objects as well as values: class patterns pull out attributes, dataclasses work with positional patterns, and nested patterns, as, guards and assert_never make parsing commands, JSON events and typed unions short and safe.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write area(shape) for the dataclasses Square(side) and Rect(w, h) using match, returning the area, and 0 for anything else.
Write kind(value) that returns "empty" for an empty list, "one" for a one-item list and "many" for the rest, using sequence patterns.
Write command(text) that splits a string and matches ["go", direction] returning "moving north" for go north, and "unknown" otherwise.
Explain it without notes
How do positional class patterns know which attribute is which?
What is the difference between a bare name and a dotted name in a case?
How does assert_never give you exhaustiveness?
Why do mapping patterns suit JSON events?
What does kind(True) return for a match that tests case int(): before case bool():, and why?
Expected output
user says 'Hi'
call weather for Pune
call clock without a city
bad message, extra keys: ['content', 'role']
a list starting with 1, then 2 more
ignored
5 -7
AssertionError: Expected code to be unreachable, but got: Neg(a=1)