Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Statements and Keywords

The match statement

Reference for Python match/case structural pattern matching: literal, sequence, mapping and class patterns, guards, captures, wildcards and OR patterns.

The match statement, added in Python 3.10, compares a value against a series of patterns and runs the block of the first one that fits. Unlike a chain of if tests, a pattern can both check the shape of the data and pull parts of it into variables in one step.

Patterns can be literals, sequences, mappings, class instances and combinations of these. It is most useful for command parsing, tree-shaped data such as ASTs or JSON, and message dispatch.

Python
match command:
    case "quit":
        stop()
    case ["go", direction]:
        move(direction)

Try it

Python Literals, sequences and captures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Mappings, classes and guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
match subject:
    case pattern1:
        block
    case pattern2 if guard:
        block
    case _:
        block
Pattern Matches
42, "text", None, True Equal literals (None, True, False by identity).
name Anything, and binds it to name.
_ Anything, binds nothing (wildcard).
Color.RED A dotted name: compares by equality with that value.
[a, b, *rest] or (a, b) A sequence (not str/bytes) of fitting length.
{"key": p, **rest} A mapping containing the keys; extra keys are allowed.
Cls(p1, attr=p2) An instance of Cls whose attributes match. Positional patterns need __match_args__ (dataclasses provide it).
p1 | p2 Either pattern (alternatives must bind the same names).
p as name The pattern, also binding the whole match to name.
case ... if cond A guard: the case only succeeds if cond is true.

Raises: nothing when no case matches; the statement is simply skipped.

Usage notes

  • Order matters. Cases are tried top to bottom, and the first match wins. Put specific patterns before general ones and _ last.
  • Bare names capture. case RED: does not compare with a variable RED; it binds anything to RED. Use a dotted name (Color.RED) or a literal.
  • Strings are not sequences here, so case [a, b] never matches "ab".
  • Mappings ignore extra keys; sequences require exact length unless a *rest is present.
  • Captured names persist after the match, as normal variables in the enclosing scope.
  • match and case are soft keywords, so they stay valid as variable names elsewhere.
  • Class patterns use isinstance checks. int() matches any integer (including True, since bool is a subclass).
  • Not a switch. It does not compile to a jump table; for a few simple constants a dict lookup or if/elif may be clearer.