Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword case

Select a match arm by testing its pattern before its optional guard.

Version: Python 3.14; repository image, production runtime not attested

Syntax

case {"qty": q} if q > 0:
    ...

Select a match arm by testing its pattern before its optional guard.

Captures bind names that the guard can inspect. A false guard allows later cases to run. A bare name captures rather than comparing an existing variable, while _ is a wildcard. The mapping pattern permits extra keys.

An unguarded irrefutable pattern such as case _: is legal only as the last case.

Examples

def label(row):
    match row:
        case {"qty": q} if q > 0:
            return f"positive:{q}"
        case {"qty": 0}:
            return "zero"
        case _:
            return "other"
print([label(row) for row in ({"qty": 2, "tag": "A"}, {"qty": 0}, {})])
try:
    compile("match 1:\n    case _: pass\n    case 1: pass", "<example>", "exec")
except SyntaxError:
    print("unreachable case")

Result

['positive:2', 'zero', 'other']
unreachable case

An unguarded irrefutable pattern such as `case _:` is legal only as the last case.

Sources