Skip to the solution
MediumDSA9 min read

What is structural pattern matching (match/case)?

1.1k views

The problem

Question presented to candidate: "Python 3.10 added match and case. Is it just a switch statement? Walk me through the kinds of patterns you can write, and tell me about a gotcha that catches people out."

What a strong answer should cover:

  • It is structural: a pattern checks the shape of the subject (type, length, keys, attributes) and binds parts of it to names, not just compares values. Cases are tried top to bottom and the first match wins; no fall-through.
  • The pattern kinds: literal, capture, wildcard _, value (dotted name), sequence (with *rest), mapping (with **rest), class (Point(x=0), positional via __match_args__), OR |, AS as, plus if guards.
  • The capture gotcha: a bare name such as case RED: binds anything; constants must be dotted (Color.RED). CPython rejects a bare-name case that is not last with a SyntaxError.
  • Rules that surprise people: str/bytes never match sequence patterns, mapping patterns ignore extra keys, case 1: matches True (== comparison) while True/False/None compare with is, and no matching case is silently a no-op.
  • When to use it: parsing commands, tagged JSON-like data, AST and message handling. A dict of handlers or plain if is still better for simple value lookups.

Code / implementation expected: Optional β€” a short match over mixed inputs using two or three pattern kinds.

  • match
  • pattern-matching

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonEvery pattern kind in one dispatcher
PythonSix gotchas: capture vs constant, str sequences, extra keys, True vs 1

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 42 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does Pydantic v2 validation work (BaseModel, field_validator, mode)?

Continue