Syntax
match subject:\n case pattern:\n # codeExamples
Basic Match Statement
Matching a value against several literal cases, similar to a switch statement.
def describe_status(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown Status"
print(describe_status(404)) # Not Found
print(describe_status(999)) # Unknown StatusMatching Multiple Values
Using '|' to match several patterns with the same result.
def classify_day(day):
match day:
case "Saturday" | "Sunday":
return "Weekend"
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return "Weekday"
case _:
return "Invalid day"
print(classify_day("Saturday")) # WeekendMatching with Guards
Adding an extra condition to a case with an if guard clause.
def categorize(age):
match age:
case n if n < 13:
return "Child"
case n if 13 <= n < 20:
return "Teenager"
case n if n >= 20:
return "Adult"
print(categorize(15)) # TeenagerMatching Data Structures
Destructuring sequences and dictionaries directly within a case pattern.
def handle_command(command):
match command:
case ["move", direction]:
return f"Moving {direction}"
case ["say", *words]:
return f"Saying: {' '.join(words)}"
case {"action": "quit"}:
return "Quitting"
case _:
return "Unknown command"
print(handle_command(["move", "north"])) # Moving north
print(handle_command(["say", "hi", "there"])) # Saying: hi there
print(handle_command({"action": "quit"})) # QuittingBest practices
- Use match/case when comparing one value against several discrete possibilities - it reads more clearly than a long if/elif chain
- Always include a case _: wildcard branch to handle values that don't match any specific pattern
- Remember match/case requires Python 3.10 or later - check your target environment before relying on it
- Take advantage of structural patterns (matching list/dict shapes) for parsing commands or structured data, not just simple value equality
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference