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|, ASas, plusifguards. - 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/bytesnever match sequence patterns, mapping patterns ignore extra keys,case 1:matchesTrue(== comparison) whileTrue/False/Nonecompare withis, 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
ifis still better for simple value lookups.
Code / implementation expected: Optional β a short match over mixed inputs using two or three pattern kinds.