case — Advanced Examples
Defines a pattern branch inside a match statement (3.10+)
Case exhaustiveness and edge cases
Ensuring all cases are handled.
python
# Simulating exhaustive matching from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 def describe_color(c): match c: case Color.RED: return "Warm color" case Color.GREEN: return "Cool color" case Color.BLUE: return "Cool color" # No wildcard - if a new variant is added, # this will return None (implicit) for c in Color: print(f"{c.name}: {describe_color(c)}") # Case with walrus-like capture data = {"type": "user", "name": "Alice", "age": 30, "role": "admin"} match data: case {"type": "user", "name": str(name), **rest}: print(f"User {name}, extra fields: {rest}")
Expected Output
RED: Warm color
GREEN: Cool color
BLUE: Cool color
User Alice, extra fields: {'age': 30, 'role': 'admin'}Use ** in mapping patterns to capture remaining keys. For exhaustive matching with enums, omit the wildcard so that missing cases return None (or add explicit error handling).
Want to try these examples interactively?
Open Advanced Playground