Class patterns, nesting, guards and as
Dataclasses get __match_args__ for free. The Pair class defines its own. Cases are tried in order.
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
circle at the origin, radius 2.0
big circle at (3, 4)
circle at Point(x=3, y=4), radius 1.0
rect 3.0x4.0 at (1, 2), area 12.0
pair 'a' and 1
unknown shape
dataclass __match_args__: ('x', 'y')