pythonintermediate
Structural Pattern Matching (match/case)
Use Python 3.10+ match/case for expressive pattern matching with guards and destructuring.
pythonPress ⌘/Ctrl + Shift + C to copy
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
@dataclass
class Circle:
center: Point
radius: float
@dataclass
class Rectangle:
origin: Point
width: float
height: float
def describe_shape(shape):
match shape:
case Circle(center=Point(0, 0), radius=r):
return f"Circle at origin with radius {r}"
case Circle(radius=r) if r > 100:
return f"Large circle with radius {r}"
case Rectangle(width=w, height=h) if w == h:
return f"Square with side {w}"
case Rectangle(width=w, height=h):
return f"Rectangle {w}x{h}"
case _:
return "Unknown shape"
# Match on dict structures
def handle_event(event: dict) -> None:
match event:
case {"type": "click", "button": "left", "x": x, "y": y}:
print(f"Left click at ({x}, {y})")
case {"type": "keypress", "key": str(k)} if len(k) == 1:
print(f"Character typed: {k}")
case {"type": t}:
print(f"Unhandled event: {t}")
# Match on sequences
def parse_command(args: list[str]) -> None:
match args:
case ["quit" | "exit"]:
print("Goodbye!")
case ["hello", name]:
print(f"Hello, {name}!")
case ["add", *items] if items:
print(f"Adding: {', '.join(items)}")
case []:
print("No command")Use Cases
- command parsing
- event handling
- shape/type dispatch
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
javabeginner
Switch Expressions — Modern Java
Use switch expressions with arrow syntax, pattern matching, guards, and yield for concise branching.
Best for: Concise branching logic replacing verbose if-else
#java#switch
scalabeginner
Pattern Matching Fundamentals
Use Scala pattern matching with guards, type patterns, tuple patterns, and nested extractors.
Best for: Control flow with pattern matching
#scala#pattern-matching
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management