Python 3.10 introduced structural pattern matching with the match / case keywords. If you’ve only used it for simple equality checks, you’re leaving most of its power on the table.
1. Destructuring sequences
You can match on the shape of a list or tuple directly:
def describe(point):
match point:
case (0, 0):
return "origin"
case (0, y):
return f"on the y-axis at {y}"
case (x, y):
return f"at {x}, {y}"
case _:
return "not a 2D point"
The (0, y) pattern binds y while requiring the first element to be exactly 0. The wildcard _ catches everything else.
2. Matching objects by type
Use class patterns to branch on type and pull out attributes at once:
match event:
case ClickEvent(x, y):
handle_click(x, y)
case KeyPress(key) if key == "Esc":
close_dialog()
case KeyPress(key):
handle_key(key)
The guard (if key == "Esc") refines a pattern without writing a nested if.
3. Capturing with starred patterns
match command.split():
case ["git", "commit", rest]:
run_commit(rest)
case ["git", rest]:
run_git(rest)
case [cmd, *rest]:
run_generic(cmd, rest)
When not to use it
match shines for parsing structured data and command dispatchers. For a simple if x == 1 or if isinstance(...), a plain if is still clearer. Reach for match when you have several related conditions on the same value’s shape.