Lesson · Control Flow
Pattern Matching
54 min readPattern Matching
Structural pattern matching can express shape-based decisions more clearly than long chains of tests. It is powerful, but it works best when the data naturally has recognizable structures.
Learning goals
- Read a
matchstatement and name the firstcasewhose pattern and guard accept a given value. - Explain why a bare name in a pattern captures instead of compares, and what that does to the cases below it.
- Destructure mappings and sequences in patterns, including one starred capture, and say what each name binds.
- Reason about guards: they run only after the structure matches, and a false guard moves execution to the next case.
- Choose between
matchand anif/elifchain based on whether the data has recognizable structure.
Mental model
A match statement is ordered shape dispatch: patterns are tested top to bottom, the first case that both fits and passes its guard wins, and every later case is skipped. If nothing fits and there is no wildcard, the statement simply does nothing.
Mental model
read it top to bottom
subject value ↓ does the next case pattern fit the shape? no → try the next case ↓ yes → is the guard (if any) true? no → try the next case ↓ yes → bind the pattern names, run this block, skip the rest
Core idea
Pattern matching dispatches on the shape of a value rather than on a chain of Boolean expressions: each case describes the structure it accepts and binds the parts it extracts. Patterns are not ordinary expressions, so one token can flip a comparison into a capture, which is why a bare name silently matches everything. Use match when the data already has recognizable structure, and keep if / elif for flat value comparisons.
match
match starts structural pattern matching. Python compares the subject against patterns in order and executes the first matching case.
case
A case contains a pattern rather than an ordinary Boolean expression. Patterns can destructure sequences, mappings, and class instances while binding names.
Literal patterns
Literal patterns are source-code forms that directly describe literal patterns values. Literal syntax is parsed by Python, so its spelling and prefixes determine the type and value created before ordinary function calls occur.
Capture patterns
A capture pattern binds the matched value to a name. A bare name normally captures rather than compares, which is a crucial difference from an ordinary equality test.
Sequence patterns
A sequence pattern destructures sequence-like subjects into element patterns and can include one starred capture for remaining items. Strings and bytes are intentionally not treated as generic sequence patterns.
Mapping patterns
A mapping pattern matches required keys and recursively matches their values. Extra keys can remain unmatched unless the pattern explicitly captures them.
Class patterns
A class pattern checks an instance type and can match selected attributes. Positional class patterns depend on __match_args__, while keyword patterns name attributes explicitly.
Guards
A guard is an if condition attached to a case. Python evaluates it only after the structural pattern matches, allowing value constraints that patterns alone cannot express.
Wildcard _
The _ pattern matches any value without binding it. It is commonly the final fallback case in a match statement.
When pattern matching is better than if/elif
When pattern matching is better than if/elif is a design question rather than a syntax rule. Use the mental model from this lesson to identify the conditions, tradeoffs, and failure modes that make one choice appropriate.
Walkthrough
describetakes one argumentvalueand runs it throughmatch value:, testing eachcasepattern in source order until one both fits and passes its guard.- The first case is a mapping pattern: it requires the keys
"name"and"age", binds their values tonameandage, then evaluatesage >= 18. The calldescribe({"name": "Mina", "age": 22})passes the structure and the guard, so the function returns"adult: Mina". - The second case
[first, *rest]destructures any sequence with at least one element, bindingfirstto element zero andrestto the remaining items as a list;describe([1, 2, 3])returnssequence starts with 1; rest=[2, 3]. case None:matches onlyNone, andcase _:is the wildcard that matches anything without binding; it sits last because everything below it would be unreachable. Predict before running: whatdescribe(None)returns, and whatdescribe("Mina")returns given that strings are excluded from sequence patterns.
Experiments to try
- Call
describe({"name": "Mina", "age": 15})anddescribe({}). Predict which case each call lands on before running; explain why the 15-year-old dict falls through even though its shape fits the first pattern. - Insert
case {"name": name}:immediately after the first case, confirm it never runs for adult dicts, then move it above and watch the output change for the same input. - Replace
case None:withcase missing:and calldescribe(42). Read the result, then explain why a bare name matches anything instead of comparing against a constant. - Rewrite
case [first, *rest]:ascase [first, second]:, adjust the return expression to the two names, and test[1, 2]against[1, 2, 3]. One matches; explain why the longer list does not.
Common mistakes
- Writing a bare name in a pattern (
case value:) to compare against a constant: a bare name is a capture pattern, so it matches everything and shadows every case below it. - Expecting a structurally matching case with a false guard to stop the match: Python falls through and keeps testing later cases, so the value can land on a less specific branch without an error.
- Expecting strings to match sequence patterns:
strandbytesare deliberately excluded, so"abc"skipscase [first, *rest]:entirely. - Assuming an unmatched
matchraises: with no matching case and nocase _:, the statement does nothing and execution continues after it, often leaving a function to returnNoneimplicitly.
Practice: Easy
- Call
describewith{"name": "Mina", "age": 22},[9, 8, 7],None, and3.14. Write down the case you expect each call to select before running, then check the returned strings against your predictions. - Change the guard to
age >= 21and find a dict whose shape fits but whose guard fails. Confirm the value reachescase _:and record the returned string. - In a small script, run
match 1:withcase True:andcase 1:branches that print distinct labels. Which branch runs first, and how doesTrue == 1explain the result?
Practice: Medium
- Add
case [x, y]:above the starred case and route[1],[1, 2], and[1, 2, 3]throughdescribe. Map each input to the case it selects and explain the routing with pattern order. - Define
class Pointwith__init__and__match_args__ = ("x", "y"), then addcase Point(x, y):. Check thatPoint(1, 2)matches while(1, 2)does not, and say what the class pattern tests that a sequence pattern does not. - Rewrite the first two cases as
if/eliftests usingisinstanceand key checks. State for which inputs the two versions disagree, if any, and which version makes the shape-based intent easier to read.
Practice: Hard
- Design a
route(command)function that accepts three shapes: a dict like{"action": "move", "dx": 1}, a tuple like("say", "hi"), and a wildcard fallback. Define the patterns and return strings, then test every shape plus one value that matches nothing. - Build a failure lab with three entries: a bare-name capture that shadows later cases, a guard that fails after a structural match, and a
matchwith no wildcard fed an unmatched value. For each entry, record whether Python raises or continues silently, and cite the rule that decides it. - Rewrite the first mapping case as
if isinstance(value, dict) and "name" in value and "age" in value and value["age"] >= 18:. List two things the pattern states more directly, and one situation where theifchain fits the data better.
Lesson checklist
- I can trace any call to
describeand name the first case whose pattern and guard accept it. - I can explain why a bare name captures instead of comparing, with a concrete example from the pattern syntax.
- I can destructure a mapping and a sequence with patterns and say what each bound name holds.
- I can state when a
matchstatement is clearer than anif/elifchain for the same data.
Remember
A `match` statement is ordered shape dispatch: patterns are tested top to bottom, a guard refines a structural match, and the first case that passes everything runs while the rest are skipped. Patterns validate and extract in one step, binding names like `first` and `rest` as they match. Remember that a failed match is silent: without `case _:`, an unmatched value simply skips the statement.
Interview angles
What is the main purpose of **match**?+
match starts structural pattern matching. Python compares the subject against patterns in order and executes the first matching case.
What should you pay attention to when using **case**?+
A case contains a pattern rather than an ordinary Boolean expression. Patterns can destructure sequences, mappings, and class instances while binding names.
How does **Literal patterns** fit into this lesson?+
Literal patterns are source-code forms that directly describe literal patterns values. Literal syntax is parsed by Python, so its spelling and prefixes determine the type and value created before ordinary function calls occur.
Why does a bare name in a pattern not behave like an equality check?+
A bare name is a capture pattern: it matches any value and binds the name, so case value: always succeeds and shadows later cases. To compare against a constant, use a literal pattern such as case 42: or move the test into a guard.