Python 3.10+astterm
ast.MatchClass
pattern matching
A class pattern case Point(x, y=0): cls is the class name, patterns the positional patterns, kwd_attrs and kwd_patterns the keyword ones.
Syntax
ast.MatchClass(cls, patterns, kwd_attrs, kwd_patterns)
It looks like a call, but no constructor runs: isinstance is checked, then attributes. Positional patterns work only if the class has __match_args__ (a dataclass sets it for you), otherwise matching raises TypeError. kwd_attrs is a list of strings, not nodes. For built-in types 'case int(n)' captures the object itself.
Examples
import ast
p = ast.parse('match o:\n case Point(x, y=0): pass').body[0].cases[0].pattern
print(type(p).__name__, p.cls.id, len(p.patterns), p.kwd_attrs) # → MatchClass Point 1 ['y']
class P:
def __init__(self, x):
self.x = x
try:
match P(1):
case P(v):
pass
except TypeError as e:
print(type(e).__name__) # → TypeError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy