A Python match statement selects a case by structural pattern and an optional guard.
Python match statements: shape matching is not input validation
Operation contract
The command boundary accepts an object with exactly operation and receipt_id, then matches a read command guarded by an exact positive integer identifier. A matching shape alone would accept the wrong field type. The explicit key check also rejects extra members instead of letting a mapping pattern silently ignore them. This fixture performs no database action; it returns a checked routing decision.
Failure and ownership boundary
A bare name in a case captures a value; it is not a comparison with a same-named local constant. Match order matters because the first successful case wins. Do not put a broad capture before a case intended to reject input. Python JSON validation: reject duplicate members and non-integer amounts reject duplicate wire members before a dictionary reaches this function.
Working program
def route_command(command):
if not isinstance(command, dict) or set(command) != {"operation", "receipt_id"}:
raise ValueError("command shape")
match command:
case {"operation": "read", "receipt_id": identifier} if type(identifier) is int and identifier > 0:
return f"read:{identifier}"
case _:
raise ValueError("command rejected")
print(route_command({"operation": "read", "receipt_id": 41}))
for command in [{"operation": "read", "receipt_id": True}, {"operation": "read", "receipt_id": 41, "tenant": "a"}]:
try:
route_command(command)
except ValueError:
print("command rejected")Output
read:41
command rejected
command rejectedCosts and limits
The accepted object has two keys, so this fixture’s matching work is bounded. Building a set of keys still visits all members before rejecting an oversized object; bound the decoded document before this stage.
Common Mistakes
- Mapping patterns allow extra keys unless your boundary rejects them.
- A captured value still needs a field contract.
Connected lessons
Python conditions and loops: distinguish no value from an empty value, Python JSON validation: reject duplicate members and non-integer amounts, Python functions: define units, validate input and return a result.
