Keywords and Control Flow

case — Match pattern and optional guard

Introduce one branch inside match. A guard is evaluated only after its pattern succeeds and can use captured names. A bare name in a pattern usually captures rather than compares; a qualified name can express a value pattern. An unguarded irrefutable case must be last. OR patterns must bind the same set of names in each alternative. Successful pattern bindings are not scoped to the case suite.

Formal Syntax & Structure

python syntaxpython
case pattern [if guard]:    suite

Working Example

Example Snippetpython
order = {"kind": "book", "quantity": 3}match order:    case {"kind": "book", "quantity": n} if n >= 2:        print("bulk", n)    case _:        print("standard")
Python Reference