brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python dataclass fields need default_factory for lists and dicts

Python
~/tips/tip-python-dataclass-default-factory

from dataclasses import dataclass, field

Gives each dataclass instance its own fresh list or dict instead of a shared default.

Mutable defaults are a classic trap, and dataclasses refuse them with an error that is easy to misread.

from dataclasses import dataclass, field

@dataclass
class Job:
    tags: list[str] = field(default_factory=list)

Writing tags: list[str] = [] raises ValueError: mutable default when the class is defined, because every instance would otherwise share one list. field(default_factory=list) calls list() for each new instance. The same goes for dict, set and any callable that builds a fresh object. Immutable defaults such as numbers, strings and tuples can stay as plain values. The error shows up at import time, so you notice it before any instance exists.

Further reading: dataclasses documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link