Introduction
Structural pattern matching (match-case) for complex data structure inspection.
Basic Match
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown"
Patterns
# Variable pattern
match value:
case x:
print(f"Got: {x}")
# Wildcard
match value:
case _:
print("Default")
# Literal pattern
match command:
case ["quit"]:
print("Quitting")
case ["move", x, y]:
print(f"Move to {x}, {y}")
# OR pattern
match status:
case 200 | 201 | 204:
print("Success")
Class Patterns
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
@dataclass
class Circle:
center: Point
radius: float
def shape_info(shape):
match shape:
case Point(x=0, y=0):
return "Origin"
case Point():
return "Some point"
case Circle(center=Point(x=0, y=0), radius=r):
return f"Centered circle, r={r}"
Practice Problems
- Implement calculator with match
- Parse command-line arguments
- Handle JSON-like structures
- Match nested patterns
- Use guards in patterns