TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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
- The interpreter evaluates the
<pattern>against the subject node. - If the
<pattern>fails to match, theaspattern fails, and no binding occurs. - If the
<pattern>succeeds, theaspattern succeeds, and the matched subject is bound to the<identifier>. - The
<identifier>is injected into the surrounding local scope (e.g., the function or module scope). Python does not enforce block-level scope formatch/casestatements, meaning the bound variable outlives thematchblock and remains accessible in the broader namespace.
case, the as pattern captures the entire subject, provided the left-hand pattern evaluates to true.
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.
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.
- Operator Precedence: The
aspattern 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 tonameas(pattern1 | pattern2) as name. - In the expression
case pattern1, pattern2 as name, theaspattern binds only to the second element, evaluated aspattern1, (pattern2 as name). To bind the entire sequence, explicit grouping is required:case (pattern1, pattern2) as name.
- In the expression
- 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.
Raises SyntaxError: multiple assignments to name ‘x’ in pattern
case [int() as x, float() as x]: passMaster Python with Deep Grasping Methodology!Learn More





