π‘ Python QuickBits β π§© Pattern Matching in Python 3.10+
Posted on: October 1, 2025
Description:
Python 3.10 introduced structural pattern matching with match/case. It looks like switch/case, but itβs smarter β you can match not just values, but also dictionary structures (like JSON) and sequences (like CLI args).
π Basic Value Matching
Use match/case like a switch statement:
command = "start"
match command:
case "start":
print("Starting process...")
case "stop":
print("Stopping process...")
case _:
print("Unknown command")
π¦ Pattern Matching JSON-like Data
You can match against a dictβs shape and extract fields directly:
import json
payload = json.loads('{"type": "user", "name": "Alice"}')
match payload:
case {"type": "user", "name": name}:
print(f"User record found: {name}")
case {"type": "order", "id": order_id}:
print(f"Order record found: {order_id}")
case _:
print("Unknown payload")
π» Matching CLI Args (Sequence Pattern)
Match lists/tuples directly β useful for CLI-like inputs:
args = ["deploy", "staging"]
match args:
case ["deploy", env]:
print(f"Deploying to {env}")
case ["rollback", env]:
print(f"Rolling back {env}")
case _:
print("Unknown command args")
β Key Points
- β Cleaner than nested if/elif.
- β Works on values, dicts, and sequences.
- β Lets you extract variables inline.
- π Available in Python 3.10 and above.
Code Snippet:
import json # to simulate JSON payload parsing
import sys # to simulate CLI args parsing
command = "start"
match command: # match on a string value
case "start":
print("Starting process...")
case "stop":
print("Stopping process...")
case _: # default case
print("Unknown command")
# Simulated JSON payload
payload = json.loads('{"type": "user", "name": "Alice"}')
match payload:
case {"type": "user", "name": name}: # extract 'name' if type=user
print(f"User record found: {name}")
case {"type": "order", "id": order_id}: # match orders
print(f"Order record found: {order_id}")
case _: # default
print("Unknown payload")
# Simulated CLI args
args = ["deploy", "staging"]
match args:
case ["deploy", env]:
print(f"Deploying to {env}")
case ["rollback", env]:
print(f"Rolling back {env}")
case _: # fallback
print("Unknown command args")
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!