0
0
PythonConceptBeginner · 4 min read

Structural Pattern Matching in Python: What It Is and How It Works

Structural pattern matching in Python is a feature introduced in Python 3.10 that lets you check a value against a pattern and extract parts of it using the 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.

python
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)))
Output
Origin On the X axis at 3 On the Y axis at 7 At coordinates (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-else statements 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 match and case.
  • 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.

Key Takeaways

Structural pattern matching lets you check and extract data based on its shape using match-case syntax.
It simplifies complex conditional logic by replacing many if-elif statements with clear patterns.
Use it when working with structured data like tuples, lists, dictionaries, or custom objects.
Introduced in Python 3.10, it improves code readability and maintainability.
Patterns can include literals, variable captures, and nested structures.