default_factory Dodges Shared Mutable Defaults
dataclass fields declare mutable defaults through field(default_factory=list), giving every instance a fresh list instead of one shared across all of them.
Code
from dataclasses import dataclass, field
@dataclass
class Tagged:
# 可变默认不能直接写 tags: list = [](dataclass 会拒绝)
tags: list = field(default_factory=list)
a = Tagged()
a.tags.append("api")
b = Tagged()
# 每个实例拿到全新的列表:互不污染
print("independent:", a.tags, b.tags, a.tags is not b.tags)
# 直接写可变默认:dataclass 构造时抛 ValueError
try:
@dataclass
class Broken:
items: list = []
except ValueError as e:
print("mutable default rejected:", type(e).__name__)Output
Captured from a sandboxed run of this snippet in the build pipeline.
independent: ['api'] [] True
mutable default rejected: ValueErrorHow the snippet works
default_factory Dodges Shared Mutable Defaults reduces to the class class.
Using it
The demo output is labeled (independent:, mutable default rejected:), so every printed line maps back to its originating operation.
Key statements
except ValueError as e:
print("mutable default rejected:", type(e).__name__)
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `dataclasses`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.