DEV Community

Cover image for Structural pattern matching in Python
MyExamCloud
MyExamCloud

Posted on

Structural pattern matching in Python

Structural pattern matching is a powerful feature in Python that allows you to make decisions based on the structure of complex data and extract desired values from it. It provides a concise and declarative way to express conditional logic and can greatly improve code readability and maintainability. In this article, we’ll explore some real case study examples of using structural pattern matching in Python.

1. Parsing API Responses
One common use case for structural pattern matching is parsing API responses. Imagine you’re working with a weather API that returns data in the following format:

{
  "current_weather": {
    "location": "New York",
    "temperature": 25,
    "conditions": "Sunny"
  }
}
Enter fullscreen mode Exit fullscreen mode

To extract the temperature from this response, you could use structural pattern matching as follows:

response = {
  "current_weather": {
    "location": "New York",
    "temperature": 25,
    "conditions": "Sunny"
  }
}

match response:
    case {"current_weather": {"temperature": temp}}:
        print(f"The current temperature in {response['current_weather']['location']} is {temp} degrees Celsius.")
    case _:
        print("Invalid response.")

Enter fullscreen mode Exit fullscreen mode

This pattern matches any dictionary with a "current_weather" key, and within that key, it matches the "temperature" value and extracts it as the variable temp. This allows you to easily access the desired data without having to write multiple if statements to check for the existence of keys.

2. Data Processing
Structural pattern matching can also be useful when working with large datasets. Imagine you have a dataset containing information about different products, including their name, category, and price. You want to filter the dataset to only include products below a certain price threshold. You could use pattern matching to extract the desired data and filter it as follows:

products = [
  {"name": "Smartphone", "category": "Electronics", "price": 500},
  {"name": "T-shirt", "category": "Clothing", "price": 20},
  {"name": "Headphones", "category": "Electronics", "price": 100},
  {"name": "Jeans", "category": "Clothing", "price": 50},
]

match products:
    case [{"category": "Electronics", "price": price} for price in range(200)] as electronics:
        print([product["name"] for product in electronics])
    case [{"category": "Clothing", "price": price} for price in range(40)] as clothing:
        print([product["name"] for product in clothing])
    case _:
        print("No products found.")

Enter fullscreen mode Exit fullscreen mode

In this example, the patterns match and extract the values based on the category and price constraints. This allows for a more concise and readable approach to filtering the dataset.

3. Validating User Input
Structural pattern matching can also be useful for validating user input. Imagine you’re creating a sign-up form for a website, and you want to ensure that the user’s email is in the correct format and that their password meets certain requirements. You could use pattern matching to perform these validations as follows:

import re

email = "test@test.com"
password = "12345"

match email:
    case _ if not re.match(r"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$", email):
        print("Invalid email format.")
    case _ if len(password) < 6:
        print("Password must be at least 6 characters.")
    case _:
        print("Sign-up successful.")

Enter fullscreen mode Exit fullscreen mode

This pattern matches and validates the email format using a regular expression, and the password length using a length check. This approach can be easily extended to include additional validations as needed.

4. Dynamically Dispatching Functions
Another interesting use case for structural pattern matching is dynamically dispatching functions based on input parameters. Imagine you’re working with a calculator program where the user can enter an operation and two numbers, and the program will perform the calculation for them. You could use pattern matching to execute the correct function based on the specified operation as follows:

from operator import add, sub, mul, truediv as div

def calculate(operator, num1, num2):
    match operator:
        case "+":
            return add(num1, num2)
        case "-":
            return sub(num1, num2)
        case "*":
            return mul(num1, num2)
        case "/":
            return div(num1, num2)
        case _:
            print("Invalid operation.")

result = calculate("*", 5, 3)
print(f"The result is: {result}")
# Output: The result is: 15

Enter fullscreen mode Exit fullscreen mode

This pattern matches the specified operator and executes the corresponding function from the operator module. This provides a compact and extensible approach to handling different operations without having to write multiple if statements.

Conclusion
Structural pattern matching is a powerful feature in Python that allows for concise, declarative, and selective code. It can be used in a variety of scenarios, from parsing API responses to validating user input and dynamically dispatching functions. By leveraging structural patterns, you can improve the readability and maintainability of your code and make complex logic more manageable.

Top comments (0)