Python📜History & Evolutionbeginner
Python 3.10 — Structural Pattern Matching (2021)
Python · History & Evolution · Run with python3
Explanation
Python 3.10 introduced `match`/`case` (PEP 634), the most syntactically significant addition since 2.0. Unlike a simple switch/case, Python's `match` is structural — it destructures data, matches by type, and binds variables in one expression. It was paired with 3.10's improved error messages (pointing at the exact column of a syntax error) and `ParamSpec` for typed higher-order functions.
Real-World Scenario
Processing HTTP responses, AST nodes, or command dispatch tables used to require chains of `isinstance` checks. `match` makes such code read like a spec rather than an implementation — the pattern mirrors the data structure you're destructuring.
Quick Snippet
snippet.py
def handle_command(command):
match command.split():
case ["quit"]:
return "Goodbye!"
case ["go", direction] if direction in ("north", "south", "east", "west"):
return f"Going {direction}"
case ["get", item, *rest]:
return f"Getting {item}" + (f" and {rest}" if rest else "")
case _:
return f"Unknown: {command}"
print(handle_command("go north")) # Going north
print(handle_command("get sword")) # Getting swordFull Example
pattern_matching.py
# Compile: python3 pattern_matching.py
# Output:
# Going north
# Getting sword
# Goodbye!
# Unknown: fly
def handle_command(command):
match command.split():
case ["quit"]:
return "Goodbye!"
case ["go", direction] if direction in ("north", "south", "east", "west"):
return f"Going {direction}"
case ["get", item, *rest]:
extra = f" and {rest}" if rest else ""
return f"Getting {item}{extra}"
case _:
return f"Unknown: {command}"
for cmd in ["go north", "get sword", "quit", "fly"]:
print(handle_command(cmd))
Run command
python3 pattern_matching.py