Phase 15 of 25 · Topic 15.5

OR Patterns (|) & AS Pattern Bindings

1Concept

The `|` operator combines multiple alternative patterns into an OR-pattern. The `as variable` syntax binds the matched sub-pattern to a variable name for downstream processing.

2Architecture Diagram

case [400 | 401 | 403 as status, msg]: ---> Matches any of the 3 status codes and binds status!

3Code Example

Python 3.12
def handle_http_status(response):
    match response:
        case (200 | 201 | 204 as code, data):
            return f"Success HTTP {code}: {data}"
        case (400 | 401 | 403 | 404 as code, error_msg):
            return f"Client Error HTTP {code}: {error_msg}"
        case (500 | 502 | 503 as code, error_msg):
            return f"Server Error HTTP {code}: {error_msg}"
        case _:
            return "Unknown Response"

print(handle_http_status((200, {"id": 101})))
print(handle_http_status((404, "Not Found")))

4Expected Output

Success HTTP 200: {'id': 101}
Client Error HTTP 404: Not Found

5Key Takeaways

  • All alternatives in an OR-pattern (`|`) must bind the exact same variable names.
  • Use `as` to name complex sub-patterns while destructuring.
  • Significantly reduces boilerplate when handling multiple HTTP or protocol status codes.