Python foundations

Python match/case: Patterns, Guards, and Examples

Match Python values or record shapes with case. Learn what a bare name captures, where a guard runs, and how to add a fallback.

Python’s match statement tests the supplied value against each case in order. The first pattern that matches and passes its optional if guard runs. Use it to recognize several shapes of data or a short list of literal values. Pattern matching requires Python 3.10 or later.

def describe(event):
    match event:
        case {"type": "note", "text": str(text)} if text.strip():
            return f"Note: {text}"
        case {"type": "closed" | "archived"}:
            return "Finished"
        case _:
            return "Unrecognized event"

assert describe({"type": "note", "text": "Read"}) == "Note: Read"
assert describe({"type": "closed"}) == "Finished"
assert describe({"type": "note", "text": ""}) == "Unrecognized event"

The first case checks that the event has type "note" and a string in "text". It binds that string to text. The guard then rejects empty or whitespace-only text. Once a case runs, Python continues after the match statement without running a later case.

Does a bare name match a constant or capture a value?

A bare name inside a pattern captures the matched value. case status: does not compare the subject to a value already stored in the variable status. A literal like case "ready": compares against the string. A qualified name such as an enum member can serve as a value pattern. To compare against an ordinary variable, use an if guard or a separate conditional.

The special name _ is a wildcard and does not capture a value. It is useful as the last branch, where it can return an explicit result for unrecognized input. If there is no fallback and no case matches, Python just continues after the statement. Decide whether that silent path makes sense for your caller.

Match an input shape carefully

Mapping patterns require the listed keys and allow extra ones. An event with "type": "note", "text": "Read", and an extra timestamp still matches the first case. If you must reject unknown keys, check them separately or capture the unmatched fields with **extras and inspect that dictionary.

Sequence patterns can check lengths and unpack values. For example, case [x, y]: matches a two-item list or compatible sequence. Strings, bytes, and bytearrays are excluded from sequence patterns. A string with two characters therefore does not match that case. If your inputs come from text commands, split or parse them before matching.

Put shared cases and specific cases in order

An OR pattern such as "closed" | "archived" can combine literal cases with identical behavior. If alternatives capture names, each alternative must bind the same set of names. That ensures the case body sees a consistent input.

Put a more specific case before a broad case that would also match it. A mapping case looking only for {"type": "note"} would catch note events before one that also checks text. Use a guard if the case needs a condition beyond the pattern, such as a nonempty string or a valid range. Keep guards straightforward. If evaluating a guard changes state, the effects can make a simple branch ordering hard to trace.

Decide if the pattern earns its place

Match/case works well when two alternatives look structurally different, such as a point represented by a pair and a comment represented by a mapping. It can also be handy for a finite list of actions. If the same dictionary maps every command to a handler function, a dispatch dictionary may be easier to maintain. A basic if statement reads naturally for “positive and less than ten.”

Try one normal value, a variant with extra fields, and an unknown shape. Include the case where a pattern matches but its guard is false. You should be able to explain which branch runs just from the pattern order and the example values.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org