Python match Statement – Structural Pattern Matching
Last updated 5 months, 1 week ago | 378 views 75 5

Python 3.10 introduced a powerful new feature: the match
statement. It brings pattern matching similar to switch
statements in other languages but with much more flexibility.
In this tutorial, you’ll learn:
-
What
match
is -
Syntax and structure
-
Pattern matching basics
-
Advanced matching (classes, guards, sequences)
-
Use cases
-
Tips and common pitfalls
-
A complete example
What Is the match
Statement?
The match
statement allows you to match values against patterns and execute code based on which pattern matches.
It’s like a smarter if...elif...else
, especially useful when dealing with structured data (e.g., dictionaries, classes, tuples).
✅ Basic Syntax
match subject:
case pattern1:
# code block
case pattern2:
# code block
case _:
# default (like else)
Example 1: Matching Constants (Like switch
)
command = "start"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case "pause":
print("Paused.")
case _:
print("Unknown command")
Example 2: Matching with Variables
value = 10
match value:
case 0:
print("Zero")
case 1 | 2:
print("One or Two")
case _:
print("Something else")
Pattern Matching with Data Structures
Example 3: Matching Tuples
point = (0, 5)
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y-axis at {y}")
case (x, 0):
print(f"X-axis at {x}")
case (x, y):
print(f"Point is at ({x}, {y})")
Example 4: Matching Lists
data = [1, 2, 3]
match data:
case [1, 2, 3]:
print("Exact match")
case [1, *rest]:
print(f"Starts with 1, rest: {rest}")
Using Guards (Conditions in Cases)
number = 10
match number:
case x if x > 0:
print("Positive number")
case x if x < 0:
print("Negative number")
case _:
print("Zero")
Matching Objects (Classes)
You can use pattern matching with class instances using dataclasses or any class with __match_args__
.
Define a Data Class
from dataclasses import dataclass
@dataclass
class User:
name: str
is_admin: bool
Match Against Object
user = User("Alice", True)
match user:
case User(name="Alice", is_admin=True):
print("Welcome Admin Alice")
case User(name=name, is_admin=False):
print(f"Welcome User {name}")
Use Case: Command Handler
def handle_command(command):
match command:
case {"action": "create", "type": "file"}:
print("Creating a file...")
case {"action": "delete", "type": "folder"}:
print("Deleting a folder...")
case {"action": action, "type": type_}:
print(f"Unhandled command: {action} {type_}")
case _:
print("Invalid command format")
Tips for Using match
-
Use
_
for default case (likeelse
). -
Match types, structures, and use guards for more control.
-
Combine cases with
|
(OR operator). -
Use
case _:
last to avoid fall-through behavior. -
Works best with Python 3.10+. Check your interpreter version!
⚠️ Common Pitfalls
Pitfall | Why It Happens | Solution |
---|---|---|
Using match in <3.10 |
SyntaxError |
Upgrade Python to 3.10+ |
Forgetting case keyword |
Python won't parse your match block |
Always start each pattern with case |
Pattern order matters | First match wins | Place specific patterns before general ones |
Using == in patterns |
Not allowed | Use pattern values, not expressions |
Full Example: Shape Matcher
shape = {"type": "rectangle", "width": 10, "height": 5}
match shape:
case {"type": "circle", "radius": r}:
print(f"Circle with radius {r}")
case {"type": "rectangle", "width": w, "height": h}:
print(f"Rectangle with area {w * h}")
case _:
print("Unknown shape")
Output:
Rectangle with area 50
Summary Table
Feature | Description |
---|---|
Keyword | match , case |
Version introduced | Python 3.10 |
Default case | case _: |
Guards | case pattern if condition: |
Uses | Cleaner branching, structured data handling |
Practice Exercise
Task: Write a program that checks whether a user is an admin, guest, or unknown based on input.
user = {"role": "admin"}
match user:
case {"role": "admin"}:
print("Access: Full")
case {"role": "guest"}:
print("Access: Limited")
case {"role": role}:
print(f"Access: Unknown role ({role})")
case _:
print("Invalid user data")
What's Next?
After mastering match
, explore:
-
Pattern matching with classes and enums
-
Combining
match
with data parsing -
Real-world use in config parsing, CLI tools, and interpreters