Python Best Practices: Using default_factory for Mutable Defaults

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.

Search

Related Posts

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran