Python Developer interview question · Most asked

Explain structural pattern matching (`match`/`case`).

Summary

Python 3.10's match statement compares a subject against patterns: literals, captures, sequences, mappings, class patterns with attributes, OR patterns (|), guards (if), and wildcards (_), destructuring data as it matches.

Longer Answer

It shines for parsing commands, ASTs, JSON-like messages and state machines. It's not a C-style switch: bare names capture values (use dotted names or literals for constants), and the first matching case wins.

Code Example

def handle(event: dict) -> str:
    match event:
        case {"type": "click", "pos": (x, y)}:
            return f"click at {x},{y}"
        case {"type": "key", "key": "q" | "Q"}:
            return "quit"
        case {"type": "resize", "size": (w, h)} if w * h > 1_000_000:
            return "large resize"
        case _:
            return "ignored"

Key Points

  • Destructures sequences, mappings, classes
  • Guards with if
  • Bare names capture (beware)
  • First match wins

More most-asked Python Developer questions

← All Python Developer questions