Structural Pattern Matching
$count++; if($count == 1) { include "../mobilemenu.php"; } ?> if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
Introduced in Python 3.10, structural pattern matching allows for more expressive and readable code when dealing with complex data structures. This feature introduces the `match` statement, which works similarly to a switch-case statement found in other programming languages but is more powerful and flexible.
Key Concepts
Match Statement: The match statement is used to begin a pattern matching block. It works similarly to a switch statement in other languages.Patterns: Patterns can match against various data structures, including tuples, lists, dictionaries, and custom objects. Patterns can also include wildcards, constants, and variable bindings.
Case Clauses: Each case clause specifies a pattern to match against. If a match is found, the corresponding block of code is executed.
1. Basic Syntax of Structural Pattern Matching
The basic syntax of the `match` statement involves matching the value of a variable against various patterns. Each pattern can be associated with a block of code that executes if the pattern matches.Example: A simple pattern match with literal values.
def match_color(color):
match color:
case "red":
return "The color is red."
case "blue":
return "The color is blue."
case "green":
return "The color is green."
case _:
return "Unknown color."
# Testing the function
print(match_color("red")) # Output: The color is red.
print(match_color("yellow")) # Output: Unknown color.
Output:
The color is red.
Unknown color.
In this example, the function `match_color` uses a `match` statement to compare the input color against various string literals. If a match is found, the corresponding return statement is executed. The underscore `_` serves as a wildcard, catching any unmatched cases. The output shows that "red" matches the first case, while "yellow" does not match any specific case, leading to the default return of "Unknown color."
2. Matching Data Structures
Structural pattern matching can also be used to match complex data structures like lists and dictionaries.Example: Matching a tuple.
def describe_point(point):
match point:
case (0, 0):
return "Origin"
case (x, 0):
return f"On the X-axis at {x}"
case (0, y):
return f"On the Y-axis at {y}"
case (x, y):
return f"Point at coordinates ({x}, {y})"
case _:
return "Not a valid point."
# Testing the function
print(describe_point((0, 0))) # Output: Origin
print(describe_point((5, 0))) # Output: On the X-axis at 5
print(describe_point((0, 3))) # Output: On the Y-axis at 3
print(describe_point((2, 3))) # Output: Point at coordinates (2, 3)
Output:
Origin
On the X-axis at 5
On the Y-axis at 3
Point at coordinates (2, 3)
3. Destructuring Patterns
Pattern matching allows destructuring of data structures directly in the case statements, enabling more concise code.Example: Matching and destructuring a dictionary.
def match_shape(shape):
match shape:
case {"type": "circle", "radius": r}:
return f"Circle with radius {r}"
case {"type": "rectangle", "width": w, "height": h}:
return f"Rectangle with width {w} and height {h}"
case _:
return "Unknown shape."
# Testing the function
print(match_shape({"type": "circle", "radius": 5})) # Output: Circle with radius 5
print(match_shape({"type": "rectangle", "width": 10, "height": 20})) # Output: Rectangle with width 10 and height 20
Output:
Circle with radius 5
Rectangle with width 10 and height 20
In this case, the `match_shape` function matches a dictionary structure representing different shapes. The case patterns destructure the dictionary to extract values directly into variables (like `r`, `w`, and `h`). The outputs show that the function correctly identifies the shape type and outputs relevant dimensions.
4. Combining Patterns
You can combine patterns to match multiple conditions in a single case.Example: Matching multiple values in one case.
def greet_user(user):
match user:
case ("admin", _):
return "Welcome, admin!"
case ("guest", _):
return "Hello, guest!"
case (name, age) if age >= 18:
return f"Hello, {name}! You're an adult."
case (name, age):
return f"Hi, {name}! You're a minor."
case _:
return "Unknown user."
# Testing the function
print(greet_user(("admin", "Alice"))) # Output: Welcome, admin!
print(greet_user(("guest", "Bob"))) # Output: Hello, guest!
print(greet_user(("Charlie", 20))) # Output: Hello, Charlie! You're an adult.
print(greet_user(("Diana", 16))) # Output: Hi, Diana! You're a minor.
Output:
Welcome, admin!
Hello, guest!
Hello, Charlie! You're an adult.
Hi, Diana! You're a minor.
The `greet_user` function demonstrates the ability to match and destructure tuples. The function uses a guard clause (`if age >= 18`) in one case to provide additional checks while allowing flexibility in pattern matching. The output confirms that each case is matched correctly based on user type and age.
5. Conclusion
Structural pattern matching in Python offers a powerful way to work with complex data structures. By allowing for the matching of various patterns, destructuring, and combining conditions, this feature significantly enhances code readability and expressiveness. As shown in the examples, it simplifies the handling of data and can replace many common control structures with a more elegant approach.