Python 3.10+astterm
ast.MatchSequence
pattern matching
A sequence pattern case [a, b] or case (a, b): patterns are the element patterns, one of which may be a MatchStar.
Syntax
ast.MatchSequence(patterns)
Square and round brackets give the same node and match list and tuple alike — 'case (a, b)' also catches [1, 2]. Strings, bytes and bytearray never match a sequence pattern, although they are sequences: 'case [a, b]' does not match 'ab'. Without a * the length must match exactly.
Examples
import ast
p = ast.parse('match x:\n case (a, *rest): pass').body[0].cases[0].pattern
print(type(p).__name__, [type(q).__name__ for q in p.patterns]) # → MatchSequence ['MatchAs', 'MatchStar']
def f(v):
match v:
case (a, b):
return 'pair'
return 'no'
print(f([1, 2]), f('ab')) # → pair no
See also
Open in the full glossarydocs.python.orgReport an inaccuracy