match and case
Matching a value against patterns rather than testing it with a chain of conditions - including patterns that destructure as they match.
Overview
The tidy version of an if-chain
match status:
case 200:
return "ok"
case 500 | 502 | 503:
return "server error"
case _:
return "unhandled"
| groups alternatives, _ is the default. The first matching case wins and the rest are skipped — there is no fall-through and no break.
If this were all match did it would be barely worth the keyword, and the page prints an if-chain beside it that agrees on every input.
match_basics.py
match_structure.py
Worth knowing
case _: is the default. Without it, no match simply falls through and nothing happens.| matches several literals in one case.case {"x": x} pulls x out for you.case Colour.RED or case 200, not a lone variable.