Python Glossary Русский

Python 3.10+astterm

ast.pattern

pattern matching

The abstract base class of match/case patterns: MatchValue, MatchAs, MatchClass, MatchSequence and others. The pattern field of match_case. Since 3.10.

Syntax

isinstance(case.pattern, ast.pattern)

Patterns are not expressions: case [x, y] gives MatchSequence, not List, and case x is a capturing MatchAs, not a Name. So searching for ast.Name in code with match misses variables bound by patterns. The wildcard _ is MatchAs with name=None and pattern=None.

Examples

import ast
src = 'match p:\n    case [x, y]:\n        pass\n    case _:\n        pass'
for case in ast.parse(src).body[0].cases:
    pat = case.pattern
    print(type(pat).__name__, isinstance(pat, ast.pattern))
# → MatchSequence True / MatchAs True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy