Python Glossary Русский

Python 3.10+astterm

ast.Match

pattern matching

The node for a match statement: subject is the expression being matched, cases a list of match_case nodes with pattern, guard and body.

Syntax

ast.Match(subject, cases)

Case patterns are not expressions: they come from a separate ast.pattern hierarchy (MatchValue, MatchAs, MatchClass…), and a walker that only knows expr will skip them. The 'if' after a pattern sits in match_case.guard as a plain expression. match and case are soft keywords: the variable match = 1 is still legal and yields an Assign.

Examples

import ast
src = 'match cmd:\n    case ["go", d] if d:\n        pass\n    case _:\n        pass'
m = ast.parse(src).body[0]
print(type(m).__name__, m.subject.id, len(m.cases))  # → Match cmd 2
c = m.cases[0]
print(type(c.pattern).__name__, c.guard.id)  # → MatchSequence d
print(type(ast.parse('match = 1').body[0]).__name__)  # → Assign

See also

Open in the full glossarydocs.python.orgReport an inaccuracy