Python — Structural pattern matching with match and case
Python 3.10 introduced match statements. Literal patterns select known values, an OR pattern shares an action, and a wildcard handles the remainder.
A simple example
Match one case
- Start with Value 2
- Do this Match case 2
- Result two
n = 2
match n:
case 2:
print("two")
case _:
print("other")
two
Route several event states to one action
Map queued and retry to the same pending action. A sent event is complete, and an unrecognized state is sent for review. Quote string literals in a case. An unqualified bare name generally captures a value rather than comparing it with a constant.
A parcel dashboard receives status updates. A queued parcel and a parcel awaiting retry both belong in the pending tray. Mark a sent parcel done and send unfamiliar statuses for review.
Run the example
Use Python 3.10 or later. Run these commands from the directory containing the example.
python3 lesson.py
def route(state):
match state:
case "queued" | "retry":
return "pending"
case "sent":
return "done"
case _:
return "review"
for state in ("queued", "retry", "sent", "unknown"):
print(route(state))
pending pending done review
Both pending states share one result. The other branches distinguish a known completion from a new or misspelled status.
Try it yourself
What should an unrecognized state such as paused produce?
Check your answer
It produces review. Add an explicit case when the application defines how to handle that state.