In Python, the match keyword is used for pattern matching, introduced in Python 3.10 as part of structural pattern matching, similar to switch statements in other languages, but far more powerful.
Introduction
What is the match Keyword?
Starting from Python 3.10, the match statement introduces structural pattern matching. It acts like a powerful switch statement found in many other languages, but with far more expressive capabilities.
Basic Example Using match
def handle(value):
match value:
case 1:
print("One")
case 2:
print("Two")
case _:
print("Something else")
This works similarly to a switch-case statement in C or JavaScript, but allows for much more than constant matching.
Traditional Approach: if–elif–else
Before Python 3.10, the typical way to implement branching logic was using if–elif chains:
def handle(value):
if value == 1:
print("One")
elif value == 2:
print("Two")
else:
print("Something else")
This is still valid and widely used, especially for simple branching logic.
Using dict for Function Dispatch
Another common Pythonic trick is to use a dictionary to map values to handler functions:
def handle_one():
print("One")
def handle_two():
print("Two")
def handle_default():
print("Default")
handlers = {
1: handle_one,
2: handle_two
}
value = 2
handlers.get(value, handle_default)()
This approach avoids multiple if–elif branches and allows dynamic behavior.
Advanced match Patterns
Matching Tuples
point = (0, 1)
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
Matching Classes
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
match p:
case Point(x=0, y=0):
print("Origin")
case Point(x, y):
print(f"Point at ({x}, {y})")
Using Wildcard _
The underscore (_) is used as a wildcard to match anything, similar to default in a switch statement:
match x:
case "a":
print("Matched a")
case _:
print("Default case")
Comparison Table
| Approach | Python Version | Use Case | Complex Matching |
|---|---|---|---|
if–elif–else |
All | Simple logic | No |
dict dispatch |
All | Function-based handling | Limited |
match |
3.10+ | Advanced pattern matching | Yes |
Summary
matchprovides clean and powerful pattern matching in Python 3.10+if–elif–elseremains universal and straightforwarddictdispatching is useful for clean function routing
- Use
if–eliffor compatibility and simplicity. - Use
dictif you’re dispatching functions by value. - Use
matchwhen working in Python 3.10+ and need readable, powerful pattern matching.
Python
- Introduction to Parquet Files: Read & Write using Python
- Python Match vs Traditional If-Elif: A Modern Take on Switch Statements
–EOF (The Ultimate Computing & Technology Blog) —
627 wordsLast Post: Auditing blockchain wallet code with Copilot AI
Next Post: Why NordVPN Is the Best Choice for Online Privacy and Security in 2025