Sub topic 4
Mutable defaults and default_factory
This chapter assumes you know how to define Python classes, that you have read the earlier chapters on @dataclass and field defaults, and that you understand the difference between mutable and immutable objects. You need Python 3.7 or newer. One behavior described below changed in Python 3.11, and the text marks it.
The shared-default problem
A default value is evaluated once, when the definition is executed, not each time it is used. Plain functions show this clearly:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['a', 'b']Both calls use the same list object, which was created when def ran. A class attribute behaves the same way: every instance that does not set its own value reads the one list stored on the class.
A dataclass default is stored the same way, as a class attribute that the generated __init__ falls back to. A plain = [] would therefore make every instance share one list. The dataclasses module refuses to let this happen.
What dataclasses reject
from dataclasses import dataclass
try:
@dataclass
class Basket:
owner: str
items: list[str] = []
except ValueError as exc:
print(exc)This prints mutable default <class 'list'> for field items is not allowed: use default_factory. The error is raised when the class is defined, not when an instance is created, so you find the mistake at import time.
Python 3.11 widened the check. Earlier versions rejected only list, dict and set defaults. From 3.11, any default whose class is unhashable (its __hash__ is None) is rejected. A regular dataclass with eq=True and no frozen=True sets __hash__ to None, so it counts as unhashable. This means that on 3.11 and newer you cannot write address: Address = Address(). On 3.10 and older that line is accepted and silently shares one Address between all instances.
default_factory builds a fresh value per instance
field(default_factory=...) takes a callable that needs no arguments. The generated __init__ calls it every time the caller does not supply that field.
from dataclasses import dataclass, field
@dataclass
class Basket:
owner: str
items: list[str] = field(default_factory=list)
currency: str = "EUR"
a = Basket("Ana")
b = Basket("Ben")
a.items.append("apple")
print(a.items) # ['apple']
print(b.items) # []
print(hasattr(Basket, "currency")) # True
print(hasattr(Basket, "items")) # FalseThe last two lines show a detail of the implementation. A field with a plain default keeps that default as a class attribute. A field with a default_factory has no class attribute at all, because there is no single value to store. The factory lives in the field's metadata object instead.
The generated __init__ behaves roughly like this:
def __init__(self, owner, items=MISSING_SENTINEL, currency="EUR"):
self.owner = owner
self.items = list() if items is MISSING_SENTINEL else items
self.currency = currencyThe real code uses an internal sentinel object for the "not supplied" marker. This means None is a legitimate value a caller can pass, and Basket("Ana", items=None) stores None.
Choosing the factory
Any zero-argument callable works. The common choices are shown below.
| Goal | Field declaration |
|---|---|
| Empty list, dict or set | `field(default_factory=list)`, `dict`, `set` |
| Nested dataclass with its own defaults | `field(default_factory=Address)` |
| Container with starting content | `field(default_factory=lambda: {"theme": "light"})` |
| Independent copy of a template | `field(default_factory=lambda: copy.deepcopy(TEMPLATE))` |
| Fresh unique or time-based value | `field(default_factory=lambda: uuid4().hex)` |
The last row matters because default_factory is not only for mutable types. Any value that should be computed per instance, such as an ID or a timestamp, needs a factory. Writing created: datetime = datetime.now() evaluates the call once at class definition, so every instance would get the same timestamp.
Here is a class that combines several of these.
from dataclasses import dataclass, field
@dataclass
class Address:
city: str = "Unknown"
@dataclass
class Customer:
name: str
address: Address = field(default_factory=Address)
tags: set[str] = field(default_factory=set)
prefs: dict[str, str] = field(default_factory=lambda: {"theme": "light"})
a = Customer("Ana")
b = Customer("Ben")
a.address.city = "Lisbon"
a.prefs["theme"] = "dark"
print(a)
print(b)The output is:
Customer(name='Ana', address=Address(city='Lisbon'), tags=set(), prefs={'theme': 'dark'})
Customer(name='Ben', address=Address(city='Unknown'), tags=set(), prefs={'theme': 'light'})Changes to Ana's nested objects do not reach Ben, because each call to Customer(...) ran the factories again.
A class is a callable, so default_factory=Address calls Address() for each customer. This only works when Address can be built without arguments.
Rules and errors
- You cannot give both
defaultanddefault_factoryfor one field. - The factory receives no arguments. It cannot read other fields. If a value depends on other fields, use
field(init=False)and compute it in__post_init__. - A field with a factory counts as having a default for ordering. A field without a default may not follow it, unless the fields are keyword-only.
- Pass the callable, not its result.
default_factory=list()hands the factory an empty list, and creating an instance fails withTypeError: 'list' object is not callable.
from dataclasses import field
try:
field(default=[], default_factory=list)
except ValueError as exc:
print(exc) # cannot specify both default and default_factoryGotchas the check does not catch
Values passed in by the caller
The factory runs only when no argument is given. If the caller passes an object, the instance stores that exact object.
shared = ["x"]
a = Basket("Ana", shared)
b = Basket("Ben", shared)
a.items.append("y")
print(b.items) # ['x', 'y']Both baskets hold the same list. If your class should own its data, copy it on the way in:
from dataclasses import dataclass, field
@dataclass
class SafeBasket:
owner: str
items: list[str] = field(default_factory=list)
def __post_init__(self):
self.items = list(self.items)
shared = ["x"]
a = SafeBasket("Ana", shared)
b = SafeBasket("Ben", shared)
a.items.append("y")
print(b.items) # ['x']Use copy.deepcopy instead of list(...) when the elements are themselves mutable. Whether to copy is a design decision. Copying costs time and surprises callers who expect aliasing, so decide it per class.
Missing annotations
Dataclasses only treat annotated names as fields. An assignment without an annotation is an ordinary class attribute, and no check runs on it.
from dataclasses import dataclass, fields
@dataclass
class Bag:
owner: str
items = [] # no annotation: not a field
x = Bag("Ana")
y = Bag("Ben")
x.items.append(1)
print(y.items) # [1]
print([f.name for f in fields(Bag)]) # ['owner']The list is shared through the class and never appears in __init__ or __repr__. If a class shows this symptom, look for a missing : type. The same applies to names annotated with ClassVar, which dataclasses also skip on purpose. Shared state of that kind should be explicit.
Frozen does not mean deeply immutable
frozen=True blocks assignment to attributes. It does not stop you from mutating a list stored in an attribute, so a frozen dataclass with a list field is still changeable and not safely hashable. For truly immutable data, prefer tuples (tuple[str, ...]) or frozenset, which are valid plain defaults:
from dataclasses import dataclass
@dataclass(frozen=True)
class Order:
sku: str
tags: tuple[str, ...] = ()
print(Order("A1")) # Order(sku='A1', tags=())Summary of the decision
- Is the default an immutable value such as a number, string, tuple, frozenset or
None? Use a plain default. - Must each instance have its own object, or a value computed at creation time? Use
default_factory. - Could the caller supply an object you do not want to alias? Copy it in
__post_init__.
Exercise
A teammate writes created: datetime = datetime.now() and log: list[str] = [] in a dataclass. Which line raises an error at class definition, what bug does the other line cause, and how do you fix both?
Show answer
The log line raises ValueError because a list is a mutable default. The created line raises no error, but datetime.now() runs once when the class is defined, so every instance gets the same timestamp. Fix both with factories: created: datetime = field(default_factory=datetime.now) and log: list[str] = field(default_factory=list).
Exercise
You have @dataclass class Team: name: str; members: list[str] = field(default_factory=list). You run roster = ["Ana"]; t1 = Team("A", roster); t2 = Team("B", roster); t1.members.append("Ben"). What does t2.members contain, and why? Write the change that makes each team own its list.
Show answer
t2.members is ['Ana', 'Ben']. The factory only runs when no value is passed, and here both teams stored the same roster object. Add def __post_init__(self): self.members = list(self.members) to the class so each instance stores its own copy.