Sub topic 4
Mutable defaults and default_factory
This chapter assumes you know how Python evaluates default argument values, the difference between mutable and immutable objects, and the basic @dataclass syntax from earlier chapters.
The shared-default trap
Python evaluates a default value once, when the function or class is defined. It does not evaluate it again on each call. With an immutable default such as 0 or "n/a" this is harmless. With a list, dict or set, every instance receives the same object.
class Basket:
def __init__(self, owner, items=[]):
self.owner = owner
self.items = items
a = Basket("Ana")
b = Basket("Ben")
a.items.append("apple")
print(b.items) # ['apple']Ben's basket now contains Ana's apple, because both instances point at one list. This is a common source of bugs in plain classes.
How dataclasses respond
A dataclass default is a class attribute, so the same trap would apply. The decorator refuses to build the class instead of letting the bug through.
from dataclasses import dataclass
try:
@dataclass
class Bad:
items: list[str] = []
except ValueError as e:
print(e)The output is mutable default <class 'list'> for field items is not allowed: use default_factory. The error is raised when the class is defined, so you see it at import time. It does not wait for the first buggy call.
Using default_factory
field(default_factory=...) takes a callable with no arguments. The generated __init__ calls it each time the caller omits that argument, so each instance gets a fresh object.
from dataclasses import dataclass, field
@dataclass
class Basket:
owner: str
items: list[str] = field(default_factory=list)
a = Basket("Ana")
b = Basket("Ben")
a.items.append("apple")
print(a.items) # ['apple']
print(b.items) # []The factory runs only when no value is passed. Basket("Cy", ["pear"]) uses the list you supplied and never calls list().
Factories for other cases
Any zero-argument callable works. Use built-in types such as dict and set directly. Use a lambda or a named function when you need a prefilled value.
from dataclasses import dataclass, field
def default_tags() -> list[str]:
return ["new"]
@dataclass
class Settings:
options: dict[str, str] = field(default_factory=lambda: {"theme": "dark"})
tags: list[str] = field(default_factory=default_tags)
seen: set[int] = field(default_factory=set)
print(Settings())Pass the function itself (default_tags). Writing default_tags() would call it once at class definition, which brings the shared-object bug back.
Rules to remember
- A field cannot have both
defaultanddefault_factory. Doing so raisesValueError. - A field with
default_factorycounts as having a default. Fields without defaults cannot follow it, and Python raisesTypeError. - The check covers unhashable defaults. Since Python 3.11 the decorator rejects any default whose class has
__hash__set toNone. That includes an instance of another non-frozen dataclass. Usedefault_factoryfor those too. Older versions only rejectedlist,dictandset. - A factory can return anything, including a nested dataclass instance:
field(default_factory=Point).
Exercise
A teammate writes tags: list[str] = field(default_factory=list()) in a dataclass. What happens, and what is the fix?
Show answer
list() is evaluated immediately and returns an empty list, so default_factory receives a list instead of a callable. Creating an instance without tags then fails with TypeError: 'list' object is not callable. The fix is to pass the callable itself: field(default_factory=list).
Exercise
Write a dataclass Inventory with a required location: str and a stock: dict[str, int] that defaults to a new empty dict for each instance. Then explain why Inventory("A").stock is Inventory("B").stock evaluates to False.
Show answer
Use stock: dict[str, int] = field(default_factory=dict) after location: str. Each call to Inventory(...) without stock runs dict() again, producing a separate object. The two stock attributes are different dicts, so is returns False.