Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The match statement, introduced in Python 3.10 via PEP 634, implements structural pattern matching. It evaluates a subject expression against a series of case blocks containing structural patterns, executing the block associated with the first successful match. Unlike traditional C-style switch statements, it performs data destructuring, variable binding, and type checking simultaneously. Both match and case are soft keywords. This language semantic means they function as reserved keywords only within the specific syntax of a pattern matching block. Developers can still use match and case as variable, class, or function names elsewhere in their code without raising a SyntaxError.
match subject_expression:
    case <pattern_1> [if <guard_condition>]:
        <action_1>
    case <pattern_2> | <pattern_3> as <variable>:
        <action_2>
    case _:
        <default_action>

Core Components

  • Subject: The expression evaluated once at the entry point of the match block.
  • Pattern: The structural definition following the case keyword. Patterns are evaluated top-to-bottom.
  • Guard: An optional if clause appended to a case. If the structural pattern matches, the guard expression is evaluated. If the guard evaluates to False, the match fails, and evaluation proceeds to the next case.
  • Wildcard (_): An irrefutable pattern that matches any subject without binding it to a variable. It is typically used as the final case to act as a default fallback.

Pattern Types and Mechanics

Literal Patterns Matches the subject against constant values (e.g., integers, strings, booleans, None). Comparison is performed using equality (==), except for singletons like None, True, and False, which are compared using identity (is).
match status_code:
    case 200:
        pass
    case None:
        pass
Capture Patterns Binds the subject (or a destructured portion of it) to a local variable using a simple, bare name. The variable is overwritten if it already exists in the current scope. Because any bare name is treated as a capture pattern, it acts as an irrefutable match for whatever subject it evaluates against.
match response:
    case error_message:
        pass # Binds the entire subject to the local variable 'error_message'
Value Patterns Matches the subject against a named constant. To distinguish a value pattern from a capture pattern, Python strictly requires named constants to be referenced via dotted names (e.g., Enum.VALUE, module.CONSTANT, or cls.CONSTANT). Attempting to match a constant using a simple, non-dotted name (e.g., case MY_CONSTANT:) is a critical pitfall: Python will interpret it as a Capture Pattern, silently matching any value, shadowing the intended constant, and introducing logical bugs.
match status:
    case HttpStatus.OK:
        pass # Value Pattern: Evaluates equality against the dotted name
    case MY_CONSTANT:
        pass # Capture Pattern: Matches ANYTHING, binding the subject to 'MY_CONSTANT'
Sequence Patterns Matches subjects that are instances of collections.abc.Sequence (e.g., list, tuple, but explicitly excluding str, bytes, and bytearray). It supports exact length matching and variable-length unpacking using the * operator.
match data_sequence:
    case [first, second]:
        pass # Matches a sequence of exactly two elements
    case [first, *rest, last]:
        pass # Binds the first, last, and packs all intermediate elements into 'rest'
Mapping Patterns Matches subjects that are instances of collections.abc.Mapping (e.g., dict). It checks for the presence of specified keys and matches their corresponding values. Extra keys in the subject do not cause the match to fail. The ** operator can capture remaining key-value pairs.
match data_dict:
    case {"id": 1, "name": name_val, **remainder}:
        pass # Matches if "id"==1, binds "name" to name_val, and captures the rest
Class Patterns Matches the subject against a specific class type and optionally destructurizes its attributes. It supports both keyword argument matching and positional argument matching. Positional matching relies on the class’s __match_args__ tuple to map positions to attribute names.
match user_object:
    case User(role="admin", age=age):
        pass # Matches User instance where role is "admin", binds the age attribute
    case Point(0, y):
        pass # Positional matching based on Point.__match_args__
OR Patterns (|) Combines multiple patterns into a single case. The match succeeds if any of the sub-patterns match. If capture variables are used, all sub-patterns must bind the exact same variables; otherwise, Python enforces this at compile time and will raise a SyntaxError (SyntaxError: alternative patterns bind different names).
match value:
    case 401 | 403 | 404:
        pass
    case {"error": code} | ["error", code]:
        pass # Both sub-patterns bind the exact same variable 'code'
AS Patterns (as) Binds a successfully matched pattern (or sub-pattern) to a specific variable name. This allows for capturing a value while simultaneously enforcing a structural or type constraint.
match payload:
    case {"type": "auth", "token": str() as token_string}:
        pass # Enforces token is a string, then binds that string to 'token_string'
Master Python with Deep Grasping Methodology!Learn More