Python Match Case
## Python Match-Case Statement (Structural Pattern Matching)
Introduced in Python 3.10, the `match...case` statement provides a powerful and expressive way to perform **Structural Pattern Matching**.
Unlike traditional `if-elif-else` chains or basic `switch-case` statements found in other languages, Python's `match...case` does not just match simple values; it can inspect the structure of complex data types (like tuples, lists, dictionaries, and custom objects), extract matching sub-patterns, and bind variables on the fly. This makes your code cleaner, more readable, and less error-prone.
---
## Syntax and Structure
The basic syntax of a `match...case` statement is as follows:
```python
match expression:
case pattern1:
# Logic for pattern1
case pattern2 if condition:
# Logic for pattern2 only if the 'if' condition (guard) is True
case _:
# Wildcard pattern: matches anything (fallback case)
```
### Key Components:
* **`match` expression**: Evaluates the subject expression that you want to match against.
* **`case pattern`**: Defines a pattern to match. This can be a literal value, a variable, a sequence, a class instance, or a wildcard.
* **`if condition` (Guard)**: An optional conditional expression appended to a case. The case matches only if the pattern matches *and* the condition evaluates to `True`.
* **`_` (Wildcard)**: A special pattern that acts as a catch-all (similar to `default` in other languages). It matches any value but does not bind it to a variable name.
---
## Code Examples
### 1. Simple Value Matching
This is the most basic form of pattern matching, equivalent to a standard switch-case statement.
```python
def match_example(value):
match value:
case 1:
print("Matched value: 1")
case 2:
print("Matched value: 2")
case _:
print("Matched other value")
match_example(1) # Output: Matched value: 1
match_example(2) # Output: Matched value: 2
match_example(3) # Output: Matched other value
```
**Output:**
```text
Matched value: 1
Matched value: 2
Matched other value
```
---
### 2. Matching Sequences and Using Guards
You can match sequences (like tuples or lists) and bind elements to variables. You can also use `if` guards to add extra conditions to a pattern.
```python
def match_example(item):
match item:
# Matches a 2-element tuple where both elements are equal
case (x, y) if x == y:
print(f"Matched equal tuple: {item}")
# Matches any other 2-element tuple
case (x, y):
print(f"Matched tuple: {item}")
# Catch-all for any other data type or structure
case _:
print("Matched other case")
match_example((1, 1)) # Output: Matched equal tuple: (1, 1)
match_example((1, 2)) # Output: Matched tuple: (1, 2)
match_example("other") # Output: Matched other case
```
**Output:**
```text
Matched equal tuple: (1, 1)
Matched tuple: (1, 2)
Matched other case
```
---
### 3. Class and Type Matching
`match...case` can inspect the type and attributes of custom objects. This is highly useful for object-oriented programming and domain-driven design.
```python
class Circle:
def __init__(self, radius):
self.radius = radius
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def match_shape(shape):
match shape:
# Matches a Circle object specifically with a radius of 1
case Circle(radius=1):
print("Matched a circle with radius 1")
# Matches a Rectangle object with width 1 and height 2
case Rectangle(width=1, height=2):
print("Matched a rectangle with width 1 and height 2")
# Matches any other shape or object
case _:
print("Matched other shape")
match_shape(Circle(radius=1)) # Output: Matched a circle with radius 1
match_shape(Rectangle(width=1, height=2)) # Output: Matched a rectangle with width 1 and height 2
match_shape("other") # Output: Matched other shape
```
**Output:**
```text
Matched a circle with radius 1
Matched a rectangle with width 1 and height 2
Matched other shape
```
---
## Key Considerations & Best Practices
1. **Python Version Requirement**: The `match...case` syntax was introduced in **Python 3.10**. It will raise a `SyntaxError` on any older Python versions.
2. **No Fall-Through**: Unlike languages like C, C++, or Java, Python's `match...case` does not require a `break` statement at the end of each case. Once a pattern matches, its block executes, and the entire `match` statement terminates.
3. **Variable Binding**: If you use a variable name in a pattern (e.g., `case x:`), it acts as a wildcard that matches any value and binds that value to the variable name `x`. If you want to match against an existing constant, use a dotted name (like `constants.PI`) or an `if` guard.
4. **Wildcard Placement**: The wildcard `case _:` must always be the last case block. Placing any case block after `case _:` will result in a syntax error because those cases would be unreachable.
YouTip