Module 16 · Lesson 02
Structural Pattern Matching
Pick data apart by its shape with match and case: literal, wildcard and or-patterns, capturing values, sequence and mapping patterns, class patterns, guards, and the traps of bare names and case order.
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Match literals and or-patterns
- Capture parts of a list
- Match dictionaries and objects
- Watch cases get tried in order
Match data by its shape
match compares a value with patterns, top to bottom, and runs the first case that fits.
Literals
case "quit":matches one exact value.|between values means or.Capture
case ["go", where]:matches a two-item list and names the second item.Shapes
Patterns can be lists, dictionaries or objects, nested inside each other.
Guards
case int(n) if n > 0:adds a test after the shape matches.
match everywhere
Any time data comes in different shapes, match keeps the code tidy.
- Game commandsTurn "go north" or "take lamp" into actions.
- Web repliesReact to a status of 200, 404 or 500 in different ways.
- Command linesPick apart
["add", name]or["remove", name, "--force"]. - EventsHandle
{"type": "click", "x": x, "y": y}and other event shapes.
Reading a case line
This case matches a two-word command, but only when the direction is a real exit. Tap each part to see its job.
Part 1 of 5
case:One pattern to try. The first case that fits wins.
Pick data apart with match
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Literals and or
Each case compares with exact values. _ catches everything else.
Your turn: Add a case for 500 that returns "Server error".
def reply(status):
match status:
case 200:
return "OK"
case 301 | 302:
return "Moved"
case 404:
return "Not found"
case _:
return "Something else"
for code in [200, 302, 404, 500]:
print(code, reply(code))Press Run to see what it prints.Watch cases get tried in order
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- def locate(point):
- match point:
- case (0, 0):
- return "origin"
- case (0, y):
- return f"up {y}"
- case (x, y) if x == y:
- return f"diagonal {x}"
- case (x, y):
- return f"at {x},{y}"
- print(locate((0, 3)))
- print(locate((2, 2)))
- print(locate((4, 1)))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Which case wins?
match 5:
case int():
print("int")
case 5:
print("five")0 of 6 answered
Common match misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
match subject:
case 1 | 2 | 3: # literals, or-pattern
...
case [x, y]: # sequence of exactly two, captured
...
case [first, *rest]: # one or more
...
case {"type": "a", "id": n}: # mapping: keys required, extras ignored
...
case Point(x=0, y=y): # class and attributes
...
case int(n) if n > 0: # type pattern with a guard
...
case ("a" | "b") as letter: # name the matched part
...
case Colour.RED: # dotted name: compares, does not capture
...
case _: # wildcard: anything else
...Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A text adventure command parser
Parse commands typed by a player: go with a direction, take with one or more items, look, and quit (also q or exit). Report anything else, including a direction that is not allowed.
def handle(command):
match command.lower().split():
case ["go", ("north" | "south" | "east" | "west") as direction]:
return f"You walk {direction}."
case ["go", other]:
return f"You cannot go {other}."
case ["take", item]:
return f"You take the {item}."
case ["take", first, *others]:
return f"You take the {first} and {len(others)} more."
case ["look"]:
return "You see a quiet forest."
case ["quit"] | ["q"] | ["exit"]:
return "Goodbye."
case []:
return "Say something."
case _:
return f"I do not understand {command!r}."
for typed in ["go north", "go up", "take lamp", "take key map rope", "LOOK", "q", "", "dance wildly"]:
print(handle(typed))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
A bare name that captures everything
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
STOP = 'stop'
def react(word):
match word:
case STOP:
return 'halt'
print(react('go'))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Payments
Handling payment webhooks
A shop receives JSON events from its payment provider: payments that succeed or fail, and refunds. Events carry extra fields the shop ignores, and the provider adds new event types over time. One match statement routes every event, and unknown ones are logged rather than crashing the handler.
Why Python fits
Mapping patterns check exactly the keys each kind of event needs and ignore extras such as currency. The refund cases show a guard: a positive whole-number amount is refunded, and the next case catches zero. A typed capture
str(kind)logs future event types, and the wildcard rejects anything without a type at all.Pythonevents = [ {"type": "payment", "status": "succeeded", "order": "A17", "amount": 4999, "currency": "usd"}, {"type": "payment", "status": "failed", "order": "A18", "reason": "card_declined"}, {"type": "refund", "order": "A11", "amount": 1500}, {"type": "refund", "order": "A12", "amount": 0}, {"type": "dispute", "order": "A05"}, {"note": "malformed"}, ] def route(event): match event: case {"type": "payment", "status": "succeeded", "order": order, "amount": amount}: return f"ship {order} (paid {amount / 100:.2f})" case {"type": "payment", "status": "failed", "order": order, "reason": reason}: return f"email customer about {order}: {reason.replace('_', ' ')}" case {"type": "refund", "order": order, "amount": int(amount)} if amount > 0: return f"refund {amount / 100:.2f} on {order}" case {"type": "refund", "order": order}: return f"ignore empty refund on {order}" case {"type": str(kind)}: return f"log unknown event type {kind!r}" case _: return "reject malformed event" for event in events: print(route(event))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Is match the same as a switch statement in other languages?
Does match work on strings character by character?
Can patterns be nested?
Which Python version do I need?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 19 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.