Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.8 — Pattern Matching in Depth
Python · Example 2 of 2 Python 3.11+

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.

01

Write area(shape) for the dataclasses Square(side) and Rect(w, h) using match, returning the area, and 0 for anything else.

02

Write kind(value) that returns "empty" for an empty list, "one" for a one-item list and "many" for the rest, using sequence patterns.

03

Write command(text) that splits a string and matches ["go", direction] returning "moving north" for go north, and "unknown" otherwise.

Explain it without notes

01

How do positional class patterns know which attribute is which?

02

What is the difference between a bare name and a dotted name in a case?

03

How does assert_never give you exhaustiveness?

04

Why do mapping patterns suit JSON events?

05

What does kind(True) return for a match that tests case int(): before case bool():, and why?

JSON events and exhaustive matching Python 3.11+
Sign in to run this example in your browser.

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)