Match/Case Pattern Types
PY · Modern Featuressyntax
match value:
case pattern:
...example
def describe(value):
match value:
case int(n) if n > 0:
return f"positive int: {n}"
case str(s) if len(s) > 5:
return f"long string: {s!r}"
case [first, *rest]:
return f"list starting with {first}, {len(rest)} more"
case {"type": "error", "code": code}:
return f"error code {code}"
case _:
return "something else"
print(describe(42))
print(describe([1, 2, 3]))
print(describe({"type": "error", "code": 500}))output
positive int: 42
list starting with 1, 2 more
error code 500Note Match/case supports literal, capture, sequence, mapping, class, guard (if), and OR (|) patterns. The _ wildcard matches anything.