Python 3.10+astterm
ast.MatchStar
pattern matching
The *name pattern inside a sequence case: it captures the remaining elements as a list; for *_ the name field is None.
Syntax
ast.MatchStar(name)
It appears only inside a MatchSequence and at most once per pattern. The captured rest is always a list, even when a tuple was matched. '*_' skips elements without binding: name=None, and no variable _ is created. The double star in a mapping pattern is not a MatchStar but the rest field of MatchMapping.
Examples
import ast
p = ast.parse('match x:\n case [h, *t]: pass\n case [*_]: pass').body[0]
print([q.name for q in p.cases[0].pattern.patterns]) # → ['h', 't']
print(p.cases[1].pattern.patterns[0].name) # → None
match (1, 2, 3):
case (first, *rest):
print(first, rest) # → 1 [2, 3]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy