KITFORMA · EDITORIAL GUIDE
How can each dataclass instance get its own list field?
KitForma editorial guide. A mutable field must be constructed per instance rather than reused as a class-level default. Dataclasses provide `field(default_factory=list)` for that purpose.
Step-by-step guidance
field(default_factory=list) for that purpose.
Declare tags: list[str] = field(default_factory=list) after importing field. Create two instances, append a tag to one, and assert the other remains empty and the lists are not identical. The factory is called without arguments, so initialization requiring another field belongs in explicit initialization logic. A frozen dataclass prevents rebinding its fields, but it does not make an embedded list immutable; use a tuple when the contents must also stay fixed.
Minimal example:
from dataclasses import dataclass, field
@dataclass
class Item:
tags: list[str] = field(default_factory=list)
a, b = Item(), Item()
a.tags.append("new")
assert b.tags == [] and a.tags is not b.tagsSources and verification
Sources checked:
Scope: This editorial guide is based on the cited sources and tool behavior. A forum question or a query observed for our site does not establish market search volume, low competition, guaranteed rankings or inadequate answers elsewhere.
This starter guide was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.