Practical Pattern Matching
Real-World Pattern Matching Scenarios
Pattern matching in Python provides powerful ways to handle complex data structures and conditional logic in practical applications.
1. Data Validation and Parsing
def validate_user_input(input_data):
match input_data:
case {'name': str(name), 'age': int(age)} if 0 < age < 120:
return f"Valid user: {name}, {age} years old"
case {'name': str(name)} if len(name) < 2:
return "Invalid name length"
case _:
return "Invalid user data"
## Example usage
print(validate_user_input({'name': 'John', 'age': 30}))
print(validate_user_input({'name': 'A'}))
2. State Machine Implementation
def process_order(order):
match order:
case {'status': 'pending', 'items': items} if len(items) > 0:
return "Processing order"
case {'status': 'completed'}:
return "Order already processed"
case {'status': 'cancelled'}:
return "Order cancelled"
case _:
return "Invalid order state"
Pattern Matching Techniques
Technique |
Description |
Example |
Structural Matching |
Match complex data structures |
case {'key': value} |
Type Checking |
Match specific types |
case x if isinstance(x, int) |
Guard Conditions |
Add additional constraints |
case x if x > 0 |
3. Error Handling and Logging
def handle_api_response(response):
match response:
case {'status': 200, 'data': data}:
return process_data(data)
case {'status': 404}:
log_error("Resource not found")
return None
case {'status': code} if 400 <= code < 500:
log_error(f"Client error: {code}")
return handle_client_error(code)
case _:
log_error("Unexpected response")
return None
Matching Flow in Complex Scenarios
graph TD
A[Input Data] --> B{Pattern Matching}
B --> |Specific Pattern 1| C[Handle Specific Case]
B --> |Specific Pattern 2| D[Handle Another Case]
B --> |Type Checking| E[Type-Based Processing]
B --> |Default Case| F[Error Handling]
Advanced Pattern Matching Patterns
Sequence Unpacking
def process_coordinates(coords):
match coords:
case [x, y]:
return f"2D Point: ({x}, {y})"
case [x, y, z]:
return f"3D Point: ({x}, {y}, {z})"
case _:
return "Invalid coordinate format"
Best Practices
- Use pattern matching for clear, readable code
- Leverage guard conditions for complex matching
- Always include a default case
- Keep patterns specific and ordered
- Pattern matching can be more efficient than multiple
if-elif
statements
- Use type hints and guard conditions for optimization
- Avoid overly complex matching logic
Explore these practical pattern matching techniques in LabEx's Python environment to enhance your coding skills!