Create Independent Defaults with field
Core idea
A mutable collection used as a default should be created separately for each record. field(default_factory=list) supplies a callable with no arguments, invoked when a default is needed. The factory can be a custom function; it must return an independent object when independence is required.
from dataclasses import dataclass,field@dataclassclass Basket: items:list[str]=field(default_factory=list)a=Basket(); b=Basket()a.items.append('bolt')print(a.items,b.items,a.items is b.items)The factory runs for both defaulted fields, producing separate lists.
Preserve explicitly supplied values
from dataclasses import dataclass,field@dataclassclass Queue: jobs:list[str]=field(default_factory=lambda:['start'])source=['custom']a=Queue(source); b=Queue()print(a.jobs is source,b.jobs)The factory only supplies the missing argument. An explicitly supplied list is not copied.
Common mistake
Use default_factory=list, not default_factory=list(). Modern dataclasses reject many mutable defaults (unhashable values since 3.11), but this is not a complete mutability test.
Practice
Build two independent settings dictionaries with a custom factory; change one and verify the other remains unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Default factory
Check your understanding of default factory.
What is printed?
from dataclasses import dataclass,field@dataclassclass A: xs:list=field(default_factory=list)print(A().xs is A().xs)What is printed?
from dataclasses import dataclass,field@dataclassclass A: xs:list=field(default_factory=lambda:[1])print(A([]).xs)What does default_factory expect?
Does a factory copy an explicitly provided list?