Python dataclasses: field(default_factory) in depth

Python dataclasses: field(default_factory) in depth

Python dataclasses automatically generate __init__, __repr__, and __eq__ from type annotations. The moment an attribute needs a mutable default value (list, dict, set), you hit a fundamental Python pitfall. field(default_factory=...) is the solution, and understanding why it is necessary changes how you reason about initialization in Python. The mutable default value trap In Python, default parameter values are evaluated once at function definition time, not at each call. This is a language property, not a bug. ...

May 19, 2026 · 5 min · Anthony

Newsletter

Get new articles delivered straight to your inbox.

No spam. Unsubscribe in one click.