Skip to main content
The as pattern in Python’s structural pattern matching (PEP 634) binds a successfully matched pattern or sub-pattern to a local identifier. It evaluates the structural condition on the left side of the as keyword and, upon a successful match, assigns the corresponding subject value to the variable name on the right side. Syntax
Evaluation Mechanics
  1. The interpreter evaluates the <pattern> against the subject node.
  2. If the <pattern> fails to match, the as pattern fails, and no binding occurs.
  3. If the <pattern> succeeds, the as pattern succeeds, and the matched subject is bound to the <identifier>.
  4. The <identifier> is injected into the surrounding local scope (e.g., the function or module scope). Python does not enforce block-level scope for match/case statements, meaning the bound variable outlives the match block and remains accessible in the broader namespace.
Structural Implementations 1. Top-Level Binding When applied at the root of a case, the as pattern captures the entire subject, provided the left-hand pattern evaluates to true.
2. Sub-Pattern Binding (Nesting) The as pattern evaluates strictly at the node level where it is defined. When nested inside sequences, mappings, or class patterns, it captures only the specific element that matched the sub-pattern, not the entire subject.
3. OR Pattern Capture The as pattern is frequently combined with the OR pattern (|). Because an OR pattern does not inherently bind the matched alternative to a variable, appending as captures whichever structural alternative successfully evaluated.
Technical Constraints and Precedence
  • Operator Precedence: The as pattern binds looser than the OR operator (|) but tighter than the open sequence operator (,).
    • In the expression case pattern1 | pattern2 as name, the OR pattern is evaluated first, meaning the entire OR expression is bound to name as (pattern1 | pattern2) as name.
    • In the expression case pattern1, pattern2 as name, the as pattern binds only to the second element, evaluated as pattern1, (pattern2 as name). To bind the entire sequence, explicit grouping is required: case (pattern1, pattern2) as name.
  • Name Collisions: Python enforces strict uniqueness for bindings within a single sequence or composite pattern. You cannot bind the same identifier multiple times within a single pattern structure. Attempting to do so raises a SyntaxError.
match subject:

Raises SyntaxError: multiple assignments to name ‘x’ in pattern

case [int() as x, float() as x]: pass
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More