Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Structural Pattern Matching in Python 3.10

Table of Contents

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

Leave a Comment

Your email address will not be published. Required fields are marked *

0
    0
    Your Cart
    Your cart is empty
    Scroll to Top

    Work with Khuyen Tran

    Work with Khuyen Tran