Python Glossary Русский

Python 3.10+astterm

ast.match_case

pattern matching

The node for one case branch of a match statement. Fields: pattern, guard (the condition after if, or None) and body, a list of statements. Since 3.10.

Syntax

ast.match_case(pattern, guard=None, body)

The condition in case x if x > 0 is kept in guard, apart from the pattern, and the pattern is a pattern node, not an expression. match_case has no lineno/col_offset of its own: take the branch position from pattern or the first body statement. Branches sit in Match.cases in order, and order matters: the first match wins.

Examples

import ast
src = 'match n:\n    case x if x > 0:\n        pass\n    case 0:\n        pass'
for case in ast.parse(src).body[0].cases:
    guard = ast.unparse(case.guard) if case.guard else None
    print(type(case.pattern).__name__, guard)  # → MatchAs x > 0 / MatchValue None
print(hasattr(case, 'lineno'))  # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy