A value pattern in Python’s structural pattern matching evaluates whether a subject is equal to the value of a specific named attribute. Defined strictly by Python’s formal grammar (PEP 634), a value pattern must be expressed as a dotted name (e.g.,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.
Constants.TARGET or HttpStatus.OK). This syntactic requirement distinguishes value patterns from literal patterns (which match raw literals like 200 or None) and capture patterns (which bind the subject to a bare identifier).
Syntax and Mechanics
A value pattern requires at least one dot (.) in the identifier name. This typically involves referencing an enumeration, a class attribute, or a module-level constant.
Evaluation Semantics
When the Python interpreter evaluates a value pattern, it performs the following steps:- It resolves the dotted name to its underlying object.
- It compares the resolved object to the subject using the equality operator (
==). - The pattern succeeds if
subject == resolved_valueevaluates toTrue.
==, standard type equality rules apply. In the example above, HttpStatus must inherit from IntEnum for the integer 200 to evaluate as equal to the enum member HttpStatus.OK. If a standard Enum were used, 200 == HttpStatus.OK would evaluate to False, and the pattern would fail to match.
The Dotted Name Requirement
A critical technical distinction in Python’s pattern matching grammar is how it differentiates between a value pattern (which compares) and a capture pattern (which assigns). To match against a pre-defined constant or variable, the pattern must be a dotted name. If a bare identifier is used, Python’s compiler interprets it as a capture pattern. A capture pattern unconditionally binds the subject to that variable name and succeeds. Becausematch/case blocks do not create a new scope, using a bare identifier overwrites (rebinds) any existing variable with that name in the current scope.
Value Patterns vs. Literal Patterns
While both pattern types are used to match specific values, Python’s grammar classifies them as distinct entities based on their syntax:- Value Pattern: Requires attribute access via a dot (
.). The value is resolved dynamically at runtime (e.g.,Color.RED,settings.DEFAULT_TIMEOUT). - Literal Pattern: Uses hardcoded literal values directly in the syntax. This includes numbers (
42), strings ("success"), and singletons (None,True,False). Literal patterns matching singletons use object identity (is) rather than equality (==).
Master Python with Deep Grasping Methodology!Learn More





