Also known as: pattern matching, structural pattern matching
The match statement (PEP 634, Python 3.10) brings structural pattern matching to Python. Its syntax is match subject: followed by one or more case pattern: blocks. Unlike C's switch, which compares against constant values, Python's match can destructure sequences, map dictionaries, check types, bind variables, and combine patterns with guards (if conditions).
Pattern types include: literal patterns (case 200:), capture patterns (case x: binds the value to x), wildcard (case _: matches anything), sequence patterns (case [first, *rest]:), mapping patterns (case {"type": "error", "msg": msg}:), class patterns (case Point(x=0, y=y):), OR patterns (case 200 | 201:), and guards (case x if x > 0:).
The match statement is particularly powerful for processing command patterns, parsing structured data (JSON, ASTs, protocol messages), and implementing state machines. It is not a replacement for simple if/elif chains — for straightforward value comparisons, if is more readable. Match statements shine when you need to simultaneously test structure and extract values from complex data.
Related terms: Conditional Statement
Discussed in:
- Chapter 4: Control Flow — Match Statements