Skip to main content
A group pattern in Python’s structural pattern matching consists of a single sub-pattern enclosed in parentheses. It is used to explicitly define evaluation precedence within complex patterns, without altering the matching semantics of the enclosed sub-pattern itself. A group pattern (P) succeeds if and only if the sub-pattern P succeeds. It does not enforce any type checking or structural constraints on the subject beyond what P already dictates.

Syntax

Mechanics and Precedence

The primary function of a group pattern is to explicitly control the parsing associativity of pattern operators, particularly the OR pattern (|) and the AS pattern (as). According to Python’s pattern matching grammar, the as operator binds less tightly than the | operator. Consequently, an as pattern cannot be directly embedded as an alternative inside an OR pattern. Group patterns are grammatically required to isolate the as binding to individual alternatives.

Disambiguation from Sequence Patterns

A critical technical distinction in Python’s pattern matching grammar is the difference between a group pattern and a sequence pattern (which matches tuples). Parentheses alone do not denote a tuple in pattern matching; the presence of a comma dictates the sequence.
  • (P): Group pattern. Matches whatever P matches.
  • (P,): Sequence pattern. Matches a sequence (like a tuple or list) containing exactly one element that matches P.
  • (): Sequence pattern. Matches an empty sequence.

Variable Binding Constraints

Group patterns can be nested arbitrarily deep. However, when using group patterns to encapsulate alternatives within an OR pattern (|), Python’s compiler strictly enforces that all alternatives bind the exact same set of variables. Failing to bind the identical variable names across all branches of an OR pattern results in a compile-time SyntaxError. This prevents runtime scenarios where a variable might be unexpectedly unbound in the case block.
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More