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

Avoiding Surprises with Mutable Default Arguments in Python

Table of Contents

Avoiding Surprises with Mutable Default Arguments in Python

Mutable default arguments in Python functions can lead to surprising and often unintended consequences. Consider this example:

def add_to_dataset(new_data, dataset=[]):
    dataset.append(new_data)
    return dataset


result1 = add_to_dataset(5)
print(f"After adding 5: {result1}")


result2 = add_to_dataset(10)
print(f"After adding 10: {result2}")
After adding 5: [5]
After adding 10: [5, 10]

The empty list [] default argument is created once at function definition, not each function call. This causes subsequent calls to modify the same list, leading to surprising results and potential data processing bugs.

To avoid this issue, use None as the default argument and create a new list inside the function:

def add_to_dataset(new_data, dataset=None):
    if dataset is None:
        dataset = []
    dataset.append(new_data)
    return dataset


result1 = add_to_dataset(5)
print(f"After adding 5: {result1}")


result2 = add_to_dataset(10)
print(f"After adding 10: {result2}")
After adding 5: [5]
After adding 10: [10]

This approach ensures that a new list is created for each function call unless explicitly provided.

By avoiding mutable defaults, you ensure that each function call starts with a clean slate, preventing unexpected side effects and making your code more predictable.

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