Python 3.10+astterm
ast.MatchAs
pattern matching
A capture pattern in a case: a bare name (case x), the wildcard (case _) or a pattern with a binding (case [a] as whole).
Syntax
ast.MatchAs(pattern=None, name=None)
One node stands for three things: 'case x' is pattern=None, name='x' and matches anything; 'case _' is pattern=None, name=None; 'case [a] as w' has a pattern and name='w'. An irrefutable capture that is not the last case is a SyntaxError 'makes remaining patterns unreachable' from compile(), although ast.parse lets it through — that is how Python catches 'case RED:' written for 'case Color.RED:'.
Examples
import ast
src = 'match v:\n case [a] as w: pass\n case x: pass'
cs = ast.parse(src).body[0].cases
print(type(cs[0].pattern.pattern).__name__, cs[0].pattern.name) # → MatchSequence w
print(cs[1].pattern.pattern, cs[1].pattern.name) # → None x
import ast
try:
compile(ast.parse('match v:\n case RED: pass\n case 1: pass'), '<m>', 'exec')
except SyntaxError as e:
print(type(e).__name__) # → SyntaxError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy