Structural dispatch
Dispatch based on the shape or contents of dictionaries, sequences, or objects.
Python · Const
case introduces a pattern-matching block inside Python’s match statement. Cases are checked in order, can bind matched values, and may include guards or a wildcard fallback.
case introduces an individual pattern-and-action block inside a match statement. Python tests cases in source order, optionally evaluates a guard after a pattern succeeds, and runs the first successful case; a wildcard can provide a fallback.
case patterns [guard] : suitecase is a soft keyword, so it remains usable as an identifier in contexts where the parser does not interpret it as part of pattern matching._ when an unmatched input needs explicit handling.def describe(value):
match value:
case {"status": "ok", "data": data}:
return f"success: {data}"
case {"status": "error", "message": message}:
return f"failure: {message}"
case _:
return "unknown"
print(describe({"status": "ok", "data": 42}))This function matches mapping shapes, binds selected values, and uses a wildcard for all other inputs.
Dispatch based on the shape or contents of dictionaries, sequences, or objects.
Extract fields from a matched value while selecting the handling branch.
Add a boolean condition after a structural pattern succeeds.
case in Python pattern matching?case defines a pattern block within match. The pattern is compared with the subject, and the block's suite runs when matching succeeds.
Follow-up: How are multiple cases selected? Python checks them from top to bottom and executes the first successful case.
A case can contain a pattern and an optional guard. The guard is evaluated after the pattern matches, and the suite runs only when that guard is true.
Follow-up: What happens when the guard is false? Python continues considering later case blocks.
case _: is the wildcard fallback. It matches when no earlier pattern succeeds, so it is useful for handling remaining input shapes.
Follow-up: Is the wildcard mandatory? No; without it, an unmatched subject simply leaves the match without selecting a case.
match statementpatternsguardswildcard pattern `_`soft keywords