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

Python Best Practices: Using default_factory for Mutable Defaults

Table of Contents

Python Best Practices: Using default_factory for Mutable Defaults

When defining classes in Python, using mutable default values for instance variables can lead to unexpected behavior.

For example, if you use a list as a default value in a class’s __init__ method, all instances of the class will share the same list object:

class Book:
    def __init__(self, title, authors=[]):
        self.title = title
        self.authors = authors


book1 = Book("Book 1")
book1.authors.append("Author 1")

book2 = Book("Book 2")
print(book2.authors)
['Author 1']

In this example, book1 and book2 share the same list object, which is why modifying the list in book1 affects book2.

To avoid this issue, you can use the default_factory parameter in dataclasses, which creates a new object for each instance:

from dataclasses import dataclass, field


@dataclass
class Book:
    title: str
    authors: list = field(default_factory=list)


book1 = Book("Book 1")
book1.authors.append("Author 1")

book2 = Book("Book 2")
print(book2.authors)  # Output: []
[]

Now, each instance has its own separate list object, and modifying one instance’s list does not affect others.

Leave a Comment

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

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran