Python 3.10+astterm
ast.MatchOr
pattern matching
An alternative pattern case 1 | 2 | 3: patterns is the list of options; the first that matches, left to right, wins.
Syntax
ast.MatchOr(patterns)
Every alternative must bind the same set of names: 'case [x] | (x, _)' is legal, while 'case [x] | 1' is a SyntaxError raised by the compiler: ast.parse builds that tree without complaint. The | here is not bitwise OR: no BinOp(BitOr) appears inside a case, and 'case Color.R | Color.G' works through MatchValue nodes inside a MatchOr.
Examples
import ast
p = ast.parse('match c:\n case 1 | 2 | 3: pass').body[0].cases[0].pattern
print(type(p).__name__, [q.value.value for q in p.patterns]) # → MatchOr [1, 2, 3]
import ast
try:
compile(ast.parse('match v:\n case [x] | 1: pass'), '<m>', 'exec')
except SyntaxError as e:
print(type(e).__name__) # → SyntaxError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy