Structural Pattern Matching in Python 3.10

Extracting data from nested structures often leads to complex, error-prone code with multiple checks and conditionals. Consider this traditional approach:

def get_youngest_pet(pet_info):
    if isinstance(pet_info, list) and len(pet_info) == 2:
        if all("age" in pet for pet in pet_info):
            print("Age is extracted from a list")
            return min(pet_info[0]["age"], pet_info[1]["age"])
    elif isinstance(pet_info, dict) and "age" in pet_info:
        if isinstance(pet_info["age"], dict):
            print("Age is extracted from a dict")
            ages = pet_info["age"].values()
            return min(ages)
    raise ValueError("Invalid input format")

# Usage
pet_info1 = [{"name": "bim", "age": 1}, {"name": "pepper", "age": 9}]
print(get_youngest_pet(pet_info1))  # Output: 1

pet_info2 = {'age': {"bim": 1, "pepper": 9}}
print(get_youngest_pet(pet_info2))  # Output: 1

Python 3.10’s pattern matching provides a more declarative and readable way to handle complex data structures, reducing the need for nested conditionals and type checks.

def get_youngest_pet(pet_info):
    match pet_info:
        case [{"age": age1}, {"age": age2}]:
            print("Age is extracted from a list")
            return min(age1, age2)
        case {'age': ages} if isinstance(ages, dict):
            print("Age is extracted from a dict")
            return min(ages.values())
        case _:
            raise ValueError("Invalid input format")

# Usage remains the same
pet_info1 = [{"name": "bim", "age": 1}, {"name": "pepper", "age": 9}]
print(get_youngest_pet(pet_info1))  # Output: 1

pet_info2 = {'age': {"bim": 1, "pepper": 9}}
print(get_youngest_pet(pet_info2))  # Output: 1
Scroll to Top