What’s Pattern Matching Again?
Pattern Matching (introduced in Python 3.10) lets you match data structures by their shape and content, kind of like switch-case but more powerful.
Example:
def handle(data):
match data:
case {"status": 200, "msg": msg}:
print("Success:", msg)
case {"status": 404}:
print("Not Found")
case _:
print("Unknown")
handle({"status": 200, "msg": "OK"})
Output:
Success: OK
Now What’s New in Python 3.14?
In Python 3.14, guard expressions become more flexible and readable.
Guards allow you to add conditions to patterns —
you can say: “Match this pattern only if a certain condition holds true.”
It’s like combining pattern matching with an if statement — but smarter and cleaner.
Example:
def check_number(data):
match data:
case {"value": v} if v > 0:
print("Positive number")
case {"value": v} if v < 0:
print("Negative number")
case {"value": 0}:
print("Zero")
case _:
print("Invalid input")
check_number({"value": 10})
Output:
Positive number
Analogy:
Imagine you’re sorting letters –
You don’t just check who it’s addressed to (the pattern),
you also check if it’s urgent or normal (the guard condition).
So you might say:
“If it’s for Alex and it says URGENT – handle immediately.”
“If it’s for Alex but not urgent – handle later.”
That’s what guard expressions do –
they add an extra filter to your matching logic.
Why It’s Useful
- Makes code cleaner and more expressive.
- Reduces nested
ifstatements. - Improves readability in complex decision logic.
- Enables smarter pattern-based data handling.
In short:
Python’s pattern matching was already like a smart filter.
Now with guard expressions, it’s like adding custom rules on top of that filter – precise, elegant, and readable.
Article written by Harshil Bansal, Team edSlash.