Use Python’s native match / case structural pattern matching (introduced in Python 3.10) as the direct, idiomatic replacement for traditional switch-case blocks, or use a dictionary dispatch mapping (dict.get(key, default)) for $O(1)$ function/value lookups and compatibility with older Python versions.
Basic Example
# 1. Recommended (Python 3.10+): match / case structural pattern matching
def handle_http_status(status: int) -> str:
match status:
case 200 | 201:
return "Success"
case 400:
return "Bad Request"
case 404:
return "Not Found"
case code if 500 <= code < 600:
return f"Server Error ({code})"
case _:
return "Unhandled Status"
print(handle_http_status(201)) # Output: "Success"
print(handle_http_status(503)) # Output: "Server Error (503)"
# 2. Classic $O(1)$ alternative (All Python versions): Dictionary dispatch
def handle_command(cmd: str) -> str:
actions = {
"start": lambda: "Service starting...",
"stop": lambda: "Service stopping...",
"restart": lambda: "Service restarting...",
}
action = actions.get(cmd, lambda: "Unknown command")
return action()
print(handle_command("start")) # Output: "Service starting..."
Key Details & Edge Cases
- No implicit fall-through in
match/case: Unlike C, Java, or JavaScriptswitchstatements, Python’smatch/caseexecutes only the first matching branch and exits automatically—you never writebreakstatements. To match multiple values in one branch, combine them with the OR pattern|(e.g.,case "y" | "yes" | "true":). - Wildcard default branch (
case _:): Always placecase _:at the bottom as the catch-all default. Placingcase _:earlier makes every subsequentcasebranch unreachable. - Variable capture pitfall in
match/case: Bare names inside acasepattern (likecase NOT_FOUND:) act as capture variables that match anything and bind it toNOT_FOUND, rather than comparing against an existing variable’s value. To match against constant values, access them via dotted attribute lookup on anEnum, class, or module namespace (e.g.,case HttpStatus.NOT_FOUND:). - Avoid eager evaluation in dictionary value lookups: If a dictionary maps keys to function call results (
{"a": expensive_fn_a(), "b": expensive_fn_b()}), Python evaluates every function upfront when building the dictionary. Store uncalled function references ({"a": expensive_fn_a, "b": expensive_fn_b}) and invoke only the selected callable afterward (handlers.get(key, default_fn)(*args)). - Structural destructuring with
match/case: Beyond simple scalar values,match/casecan unpack sequences, dictionaries, and class attributes directly (e.g.,case {"action": "move", "x": x, "y": y}:), making it vastly more expressive thanif / /chains for nested payloads or AST/JSON routing.
Comparison of Switch-Case Alternatives in Python
| Approach | Python Version | Lookup Complexity | Supports Complex Patterns / Guards? | Best Used When |
|---|---|---|---|---|
match / case |
Python 3.10+ | $O(n)$ sequential branch check | Yes (` | , if` guards, tuple/dict/object unpacking) |
Dictionary Dispatch (dict.get) |
All versions | $O(1)$ hash lookup | No (exact hashable key match only) | Mapping discrete keys/commands directly to functions or constant values. |
if / elif / else chain |
All versions | $O(n)$ sequential evaluation | Yes (arbitrary boolean expressions) | Short 2–4 branch checks or conditions involving dynamic variable comparisons. |
Class / getattr / Polymorphism |
All versions | $O(1)$ attribute/vtable dispatch | Via subclassing or .singledispatch |
Extensible plugin handlers, state machines, or type-based dispatch. |
You must log in or register to comment.
