Match Syntax Basics
Introduction to Match Statement
In Python 3.10+, the match
statement introduces a powerful pattern matching mechanism that provides a more elegant and concise way to handle complex conditional logic compared to traditional if-elif-else
structures.
Basic Syntax Structure
match subject:
case pattern1:
## Action for pattern1
case pattern2:
## Action for pattern2
case _:
## Default case (wildcard)
Pattern Matching Types
Literal Matching
def describe_value(value):
match value:
case 0:
return "Zero"
case 1:
return "One"
case _:
return "Other number"
## Example usage
print(describe_value(0)) ## Output: Zero
Sequence Matching
def process_sequence(seq):
match seq:
case []:
return "Empty list"
case [x]:
return f"Single element: {x}"
case [x, y]:
return f"Two elements: {x}, {y}"
case [x, *rest]:
return f"First element: {x}, Remaining: {rest}"
## Examples
print(process_sequence([])) ## Output: Empty list
print(process_sequence([1])) ## Output: Single element: 1
print(process_sequence([1, 2])) ## Output: Two elements: 1, 2
print(process_sequence([1, 2, 3, 4])) ## Output: First element: 1, Remaining: [2, 3, 4]
Object Matching
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def describe_point(point):
match point:
case Point(x=0, y=0):
return "Origin"
case Point(x=0, y=y):
return f"On Y-axis at {y}"
case Point(x=x, y=0):
return f"On X-axis at {x}"
case _:
return "General point"
## Usage
origin = Point(0, 0)
y_point = Point(0, 5)
x_point = Point(3, 0)
general_point = Point(2, 3)
print(describe_point(origin)) ## Output: Origin
print(describe_point(y_point)) ## Output: On Y-axis at 5
print(describe_point(x_point)) ## Output: On X-axis at 3
print(describe_point(general_point)) ## Output: General point
Key Characteristics
Pattern Matching Features
Feature |
Description |
Exhaustiveness |
Compiler checks for complete pattern coverage |
Destructuring |
Easily extract and bind values |
Wildcard Matching |
Use _ for catch-all scenarios |
Best Practices
- Use pattern matching for complex conditional logic
- Prefer readability over complexity
- Utilize wildcard patterns for default cases
Flow Visualization
flowchart TD
A[Start Match Statement] --> B{Evaluate Subject}
B --> |First Pattern| C[Match Pattern 1]
B --> |Second Pattern| D[Match Pattern 2]
B --> |No Match| E[Wildcard/Default Case]
Conclusion
The match
statement in Python provides a robust and expressive way to handle pattern matching, offering more flexibility and readability compared to traditional control structures.