Python 3.10+Conditionalsconstruct
match / case
pattern matching
Structural pattern matching (Python 3.10+): a value is matched against literals, types and structures; case _ catches everything else.
Syntax
match subject:
case pattern1: ...
case pattern2 if guard: ...
case _: ...
The main trap: a bare name in a case does not compare against an existing variable — it captures, always matching and binding the value to that name. To match a constant you need a literal or a dotted name (for example Status.OK), otherwise that case swallows everything. Available only in Python 3.10 and later.
Examples
match "quit":
case "quit": print("выход") # → выход
case "help": print("помощь") # не выполнится: сработал первый case
case _: print("неизвестно")
point = (0, 1)
match point:
case (0, 0): print("начало")
case (0, y): print(f"ось Y, y={y}") # → ось Y, y=1
case (x, y) if x == y: print("диагональ")
case _: print("общий")
match 42:
case int(n) if n > 10: print(f"большое {n}") # → большое 42
case _: print("другое")
See also
Open in the full glossarydocs.python.orgReport an inaccuracy