Structural Pattern Matching in Python: What It Is and How It Works
match and case keywords. It works like a smarter switch statement that can look inside complex data structures and decide what to do based on their shape and content.How It Works
Structural pattern matching works by comparing a value to different patterns in a match block. Think of it like sorting mail: you look at each envelope and decide what to do based on the address and stamps. Here, the patterns are like rules that check if the value fits a certain shape or contains specific parts.
When Python finds a pattern that fits, it runs the code inside that case. You can also pull out pieces of the value, like grabbing the city from an address, and use them inside the code. This makes it easy to handle complex data like lists, dictionaries, or custom objects without writing many if statements.
Example
This example shows how to use structural pattern matching to check the shape of a point and print a message based on its coordinates.
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"At coordinates ({x}, {y})" print(describe_point((0, 0))) print(describe_point((3, 0))) print(describe_point((0, 7))) print(describe_point((4, 5)))
When to Use
Use structural pattern matching when you need to check complex data structures and want clear, readable code. It is great for:
- Handling different shapes of data like tuples, lists, or dictionaries.
- Extracting parts of data easily without extra code.
- Replacing long chains of
if-elif-elsestatements with cleaner, more understandable code. - Working with custom classes by matching their attributes.
For example, it helps when processing messages, commands, or data formats where the structure matters.
Key Points
- Introduced in Python 3.10 using
matchandcase. - Matches values based on their structure, not just equality.
- Can extract parts of data into variables.
- Makes code easier to read and maintain for complex conditions.