Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python match statements: shape matching is not input validation

Last updated: 30 Sept 20264 min read
tutorial
BeginnerBy AITrove Editorial

A Python match statement selects a case by structural pattern and an optional guard.

Download Python source kit

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

python
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

Output
read:41
command rejected
command rejected

Costs 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.

Related Python operation checks

Python Enum: parse wire values into a closed state set.

python
pattern-matching
Storage details