Course contentsShow
← Python
Lesson 472 of 1,0607. Object-Oriented ProgrammingFree lesson

Handling Field Defaults with Factory Functions

Use field(default_factory=...) to correctly handle mutable default values like lists or dictionaries within dataclasses.

In this lesson, you will learn how to safely initialize mutable fields in dataclasses using default_factory.

The Problem with Mutable Defaults

When working with dataclasses, you might be tempted to set a default value for a list or dictionary like this:

from dataclasses import dataclass

@dataclass
class Team:
    # Danger: This will share the same list instance across all objects!
    members: list = [] 

In Python, dataclass defaults are evaluated only once when the class is defined. If you use a mutable object like [] or {}, every instance of Team will share the exact same list object in memory. If you add a member to one team, it will accidentally appear in every other team created!

The Solution: default_factory

To ensure every new instance gets its own unique, empty container, we use the field function combined with a default_factory. This tells the dataclass to "call this function" every time a new object is created, rather than reusing a single pre-defined value.

from dataclasses import dataclass, field

@dataclass
class Team:
    # Each time a Team is created, list() is called to produce a fresh list
    members: list = field(default_factory=list)
    # You can also use dict for dictionaries
    metadata: dict = field(default_factory=dict)

# Usage
team_a = Team()
team_b = Team()

team_a.members.append("Alice")
print(team_a.members)  # ['Alice']
print(team_b.members)  # [] (Correctly remains empty)

Why it works

The default_factory argument expects a callable (like list, dict, or a custom function). Because the dataclass executes this callable during the __init__ process for every new instance, it guarantees that your mutable fields start with brand-new, independent memory allocations. This is the idiomatic way to prevent accidental side effects between your objects.

Key Takeaway: Always use field(default_factory=...) when initializing mutable types like lists or dictionaries in a dataclass to ensure each instance maintains its own independent state.