Practical Matching Examples
Real-World Pattern Matching Scenarios
Pattern matching in Python offers powerful solutions for complex data processing and decision-making tasks. This section explores practical applications across different domains.
1. Command-Line Argument Processing
def process_command(command):
match command.split():
case ['create', resource]:
return f"Creating {resource}"
case ['delete', resource]:
return f"Deleting {resource}"
case ['update', resource, *details]:
return f"Updating {resource} with {details}"
case _:
return "Invalid command"
## Usage examples
print(process_command("create user"))
print(process_command("update server config prod"))
2. JSON Data Parsing
def analyze_user_data(user):
match user:
case {'name': name, 'age': age} if age >= 18:
return f"Adult user: {name}"
case {'name': name, 'age': age} if age < 18:
return f"Minor user: {name}"
case {'name': name}:
return f"User without age: {name}"
case _:
return "Invalid user data"
3. State Machine Implementation
stateDiagram-v2
[*] --> Idle
Idle --> Processing: start
Processing --> Completed: success
Processing --> Failed: error
Completed --> [*]
Failed --> [*]
class WorkflowManager:
def process_state(self, state, event):
match (state, event):
case ('idle', 'start'):
return 'processing'
case ('processing', 'success'):
return 'completed'
case ('processing', 'error'):
return 'failed'
case _:
return state
4. Error Handling and Type Checking
def safe_divide(a, b):
match (a, b):
case (int() | float(), int() | float()) if b != 0:
return a / b
case (_, 0):
return "Division by zero"
case _:
return "Invalid input types"
Pattern Matching Complexity Comparison
Scenario |
Traditional Method |
Pattern Matching |
Command Processing |
Multiple if-else |
Concise matching |
Data Validation |
Nested conditionals |
Declarative style |
Type Checking |
Type() checks |
Integrated matching |
5. Configuration Management
def configure_system(config):
match config:
case {'mode': 'production', 'debug': False}:
return "High-performance mode"
case {'mode': 'development', 'debug': True}:
return "Full debugging enabled"
case {'mode': mode} if mode in ['staging', 'test']:
return f"{mode.capitalize()} environment"
case _:
return "Invalid configuration"
Advanced Techniques
- Combine pattern matching with type hints
- Use structural pattern matching for complex data structures
- Leverage conditional matching for sophisticated logic
Best Practices
- Keep patterns specific and ordered
- Use default cases for comprehensive handling
- Prefer readability over complexity
In the LabEx Python learning environment, developers can experiment with these advanced pattern matching techniques to write more expressive and concise code.