The mapping pattern is a structural pattern matching construct introduced in Python 3.10 used to destructure and validate objects that implement the mapping protocol. It verifies the presence of specific keys and applies sub-patterns to their corresponding values, inherently allowing for partial matches by ignoring unspecified keys in the subject.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.
Syntax
Core Mechanics
- Type Validation: The pattern checks if the subject’s class has the
Py_TPFLAGS_MAPPINGflag set at the C level. This includes built-in types likedictand classes that explicitly inherit fromcollections.abc.Mapping. Classes registered merely as virtual subclasses viacollections.abc.Mapping.register()will fail mapping pattern matching because they lack this C-level flag, even thoughisinstance(subject, Mapping)evaluates toTrue. - Key Presence: The pattern checks if all keys defined in the
casestatement exist in the subject. - Value Destructuring: If the keys exist, the pattern evaluates the corresponding values against the provided
value_pattern. - Partial Matching: Unlike sequence patterns, mapping patterns are partial by default. If the subject contains keys not specified in the pattern, the match will still succeed.
Syntax Variations and Visualization
Basic Key-Value Matching and Binding Values can be matched against literals, types, or bound to variables for use within the case block.int, str, float, and bool), the pattern matching engine treats them as special cases that accept a single positional sub-pattern. This allows you to validate the type and bind the value simultaneously using syntax like int(uid).
** Unpacking)
You can capture all unspecified key-value pairs into a new dictionary using the double-asterisk prefix.
Technical Constraints
- Key Restrictions: Keys within the pattern must be literal patterns (e.g., strings, numbers, booleans,
None) or value patterns (e.g.,Enummembers accessed via dotted names). You cannot use bare variables to dynamically match keys, as bare variables are treated as capture patterns.
- Duplicate Keys: Defining duplicate keys within a single mapping pattern raises a
SyntaxErrorat compile time. - Single Unpacking: Only one
**binding is permitted per mapping pattern, and it must be the final item in the pattern definition. - No
**_Wildcard: While**restis valid for capturing remaining items, using**_to explicitly ignore remaining items is aSyntaxError. Because mapping patterns are partial by default,**_is redundant.
Master Python with Deep Grasping Methodology!Learn More





