Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

How Python Dataclass Default Values Work

Python dataclass default values: how immutable defaults work, why mutable defaults raise an error, and when to use default_factory for independent per-instance state.

~4 min readPython
#python#dataclasses#default_factory#mutable-defaults
Illustration of Python dataclass default values showing a shared mutable list versus per-instance default_factory lists.

Python dataclass default values look simple at first: assign a literal to the field and move on. The syntax is straightforward for immutable types:

python
from dataclasses import dataclass @dataclass class Config: retries: int = 3 timeout: float = 30.0 label: str = "default"

This works because int, float, and str are immutable. The default is evaluated once at class definition time, and every instance that omits the argument shares that same default object. Since the value cannot be mutated, sharing is harmless.

The problem appears the moment you try to use a mutable default like a list or dict:

python
@dataclass class Task: tags: list = [] # raises ValueError

This raises a ValueError at class definition time, because the default would be shared across all instances — mutating task1.tags would also change task2.tags. Dataclasses reject this rather than letting the bug surface later in production.

Using default_factory for Mutable Values

The fix is field(default_factory=...):

python
from dataclasses import dataclass, field @dataclass class Task: tags: list = field(default_factory=list)

The factory is called once per instance, so each Task receives its own empty list. You can pass any callable that returns the default value:

python
from datetime import datetime @dataclass class Task: tags: list = field(default_factory=list) metadata: dict = field(default_factory=dict) created_at: datetime = field(default_factory=datetime.now)

Note that datetime.now is passed as the callable, not datetime.now(). Passing the result of the call would evaluate it once at class definition time, so every instance would get the same creation time rather than a fresh one.

When the Default Is Evaluated

The timing difference is the core of the behavior. field(default=...) evaluates the default once, when the class is defined. field(default_factory=...) evaluates the factory each time an instance is created.

For immutable defaults, the single evaluation is fine because the value cannot be mutated. For mutable defaults, the factory must run per instance to give each object independent state.

There is a subtle interaction with init=False:

python
@dataclass class Task: created_at: datetime = field(init=False, default_factory=datetime.now) tags: list = field(default_factory=list)

Here created_at is not accepted as a constructor argument, but the factory still runs at instance creation, so each Task records its own creation time without the caller supplying one.

Choosing Between default and default_factory

SituationWhat to use
Immutable value such as int, str, float, tupledefault=...
Mutable value such as list, dict, setdefault_factory=...
Value that must be computed at instance creationdefault_factory=...

A tuple is immutable in structure, so field(default=()) is safe. If you need a list-like default but want to avoid a factory, a tuple of immutable values can be a simpler alternative, though it changes the field's type. Be careful not to put a mutable object inside that tuple, because the nested object would still be shared.

Common Failure: Passing the Call Result

A frequent mistake is writing field(default_factory=[]) or field(default_factory=datetime.now()). In both cases, the expression is evaluated at class definition time, and the resulting object — a list or a datetime — is not callable. The @dataclass decorator detects this immediately and raises TypeError: default_factory must be callable, rather than waiting until an instance is created.

The fix is to pass the callable itself. If you need to parametrize the factory, use a lambda or a named function:

python
@dataclass class Task: tags: list = field(default_factory=lambda: ["untagged"])

Lambdas work, but a named factory function is easier to test and reuse when the logic grows beyond a single expression.

Frozen Dataclasses and Defaults

In a frozen dataclass, frozen=True prevents attribute assignment after construction. Defaults still behave the same way. Frozen does not make mutable defaults safe: a frozen dataclass can still contain a list that is mutated through a method, so default_factory remains the correct choice for mutable fields.

Operational and Maintainability Considerations

The choice between default and default_factory affects more than correctness. A factory that performs I/O or heavy computation at instance creation adds cost to every construction. If the default is expensive, consider whether it belongs in the dataclass at all, or whether a lazy property is more appropriate.

Factories also affect serialization. If you use asdict() to convert a dataclass to a dict, the default values appear in the output. That is usually fine, but if a default is derived from a global setting, the serialized value may not match the current configuration at deserialization time.

One more maintainability point: do not use a mutable default to mean "shared state on purpose." If two instances must share a list, pass the same list into both constructors rather than relying on a class-level default. The dataclass machinery deliberately prevents the implicit shared default, and working around it with a custom __post_init__ only obscures the intent.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.