The OR pattern is a structural pattern matching construct in Python (introduced in version 3.10 via PEP 634) that allows a singleDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
case block to match a subject value against multiple alternative sub-patterns. It is denoted by the pipe character (|) and evaluates alternatives sequentially, succeeding if any of the specified sub-patterns successfully match the subject.
Syntax
Execution Mechanics
- Left-to-Right Evaluation: The Python interpreter evaluates the sub-patterns separated by
|strictly from left to right. - Short-Circuiting: Evaluation stops immediately upon the first successful match. Subsequent sub-patterns in the same
casestatement are not evaluated. - Sub-pattern Composition: The OR pattern can combine literal patterns, value patterns, sequence patterns, mapping patterns, or class patterns.
Name Binding Rules
When using capture patterns (variable binding) within an OR pattern, Python enforces strict structural equivalence regarding the bound names. Every alternative within the OR pattern must bind the exact same set of variables. If the alternatives bind different variables, or if one alternative binds a variable while another does not, the interpreter raises aSyntaxError at compile time.
Valid Binding:
SyntaxError):
Wildcards in OR Patterns
Python explicitly forbids using the wildcard pattern (_) as an alternative within an OR pattern. Attempting to include a wildcard as a sub-pattern in an OR pattern will raise a SyntaxError.
Invalid Wildcard Usage (SyntaxError):
Nesting OR Patterns
The OR pattern does not have to exist at the top level of thecase statement. It can be nested deeply within sequences, mappings, or class patterns to create highly specific structural constraints.
Nested within a Sequence:
Precedence and the AS Pattern
In Python’s pattern matching grammar, the OR pattern (|) has higher precedence than the AS pattern (as). Consequently, an as binding at the end of an OR pattern applies to the entire OR pattern, not just the immediately preceding sub-pattern. Parentheses are not required to bind the result of the entire OR pattern.
Valid Binding:
SyntaxError):
Master Python with Deep Grasping Methodology!Learn More





