Match the shape of sequences and mappings instead of writing many indexing checks.
What You Will Learn
A sequence pattern such as [x, y] requires two positional elements, while [first, *rest] accepts more. A mapping pattern checks required keys and can ignore extra keys. Strings are not matched by ordinary sequence patterns. Pattern matching should clarify known message shapes, not substitute for validating untrusted input.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
def interpret(message):
match message:
case ["move", x, y]:
return f"Move to ({x}, {y})"
case {"action": "stop", "reason": reason}:
return f"Stop: {reason}"
case _:
return "Unknown message"
print(interpret(["move", 3, 4]))
print(interpret({"action": "stop", "reason": "complete"}))
How the Example Works
- The function interpret defines reusable behavior; its body executes when it is called, not when it is declared.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
Move to (3, 4)
Stop: complete
When You Would Use This
Decide which input types are valid, what output should be produced, and which cases should fail clearly. A small self-contained demonstration is a good starting point before adding file access, network calls, or application state.
Practice: Modify the Code
Match ["sum", *values] and sum the captured values after checking their types.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming a mapping pattern requires an exact match with no additional keys.
- Forgetting that a two-element sequence pattern will not match a three-element list.
Key Takeaways
- Match the shape of sequences and mappings instead of writing many indexing checks.
- A sequence pattern such as [x, y] requires two positional elements, while [first, *rest] accepts more.
- Apply this operation only after checking the assumptions and input conditions shown in the example.