Python 3.10+astterm
ast.MatchMapping
pattern matching
A mapping pattern case {'k': v, **rest}: keys are key expressions, patterns the value patterns, rest the name for the remainder or None.
Syntax
ast.MatchMapping(keys, patterns, rest)
Unlike a sequence, a mapping pattern does not require an exact match: 'case {"x": x}' also catches a dict with extra keys. The '**rest' remainder is not a node but a string in the rest field. A key may only be a literal or a dotted name, and it is looked up with get, so a defaultdict gains no new keys during matching.
Examples
import ast
p = ast.parse('match x:\n case {"id": i, **rest}: pass').body[0].cases[0].pattern
print(type(p).__name__, [k.value for k in p.keys], p.rest) # → MatchMapping ['id'] rest
match {'id': 7, 'extra': 1}:
case {'id': i}:
print('id', i) # → id 7
See also
Open in the full glossarydocs.python.orgReport an inaccuracy