@dataclass removes so much boilerplate that it’s easy to forget it is still generating a normal class with normal Python semantics underneath. Most of its surprises come from that gap: what you wrote looks declarative, but what runs is an __init__ with default arguments, a class body with class attributes, and a __hash__ that may or may not exist.
All output below was verified on CPython 3.13.14.

The error everyone hits first
Write the obvious thing and Python stops you at class-definition time:
from dataclasses import dataclass
@dataclass
class Cart:
items: list = []
# ValueError: mutable default <class 'list'> for field items
# is not allowed: use default_factory
This is the classic def f(x=[]) bug: a default is evaluated once, when the class body executes, so every instance would share the same list. Nice of Python to catch it. The fix is default_factory, a zero-argument callable invoked per instance:
from dataclasses import dataclass, field
@dataclass
class Cart:
items: list[str] = field(default_factory=list)
meta: dict[str, str] = field(default_factory=dict)
So far, so well-documented. The interesting part is where the guard stops working.
The blind spot: the guard tests hashability, not mutability
CPython cannot detect mutability, so it uses unhashable as a proxy for it. In 3.11+ the check is essentially if f.default.__class__.__hash__ is None (before 3.11 it was a hardcoded isinstance(f.default, (list, dict, set))). Either way, a mutable class that keeps its default __hash__ sails straight through:
from dataclasses import dataclass
class Bag: # mutable, but hashable by identity
def __init__(self):
self.data = []
@dataclass
class Session:
bag: Bag = Bag() # no error, no warning
a, b = Session(), Session()
a.bag.data.append("x")
print(b.bag.data) # ['x'] <-- leaked
print(a.bag is b.bag) # True <-- one object for all instances
This is the exact bug the guard exists to prevent, and it is silent. It bites hardest with the objects you’d never think of as “defaults”: a Bag-like accumulator, an ORM query builder, an httpx.Client, a custom config holder.
Rule of thumb: if a default is anything other than an immutable scalar (int, str, bool, None, frozenset, tuple of immutables) or an enum member, use default_factory — do not wait for ValueError to tell you.
@dataclass
class Session:
bag: Bag = field(default_factory=Bag) # fresh Bag per instance
default_factory silently removes the class attribute
A plain default lives on the class. A default_factory does not — it only exists inside __init__:
@dataclass
class Config:
name: str = "anon"
tags: list[str] = field(default_factory=list)
Config.name # 'anon'
Config.tags # AttributeError: type object 'Config' has no attribute 'tags'
If you have code that introspects defaults via SomeClass.field_name (validation layers, admin forms, serializers), it will work for half your fields and blow up on the other half. Read defaults through dataclasses.fields() instead, where they appear as f.default / f.default_factory with a MISSING sentinel.
Field order is a hard constraint, and inheritance makes it worse
Because fields become positional parameters of __init__, a field without a default can never follow one with a default:
@dataclass
class Base:
a: int = 0
@dataclass
class Child(Base):
b: int
# TypeError: non-default argument 'b' follows default argument 'a'
Nothing is wrong with Child in isolation — it inherits Base‘s fields first, so the order is a=0, b. Any base class that gives everything a default effectively forbids required fields in every subclass. Since 3.10, kw_only dissolves the whole problem by moving the field out of the positional signature:
@dataclass
class Child(Base):
b: int = field(kw_only=True)
Child(b=5) # Child2(a=0, b=5)
For class hierarchies, @dataclass(kw_only=True) on every class is the low-drama default: order stops mattering and call sites become self-documenting.
frozen=True is shallow, and it rewires __hash__
frozen=True blocks attribute rebinding. It says nothing about the objects your attributes point to:
@dataclass(frozen=True)
class Tagged:
tags: list[str] = field(default_factory=list)
t = Tagged()
t.tags.append("mutated") # fine — the list is not frozen
print(t.tags) # ['mutated']
t.tags = [] # FrozenInstanceError
If you want actual immutability, hold immutable values: tuple[str, ...] with field(default_factory=tuple), or wrap mappings in types.MappingProxyType.
The second half is hashability, which follows rules worth memorising:
@dataclass # eq=True, frozen=False
class Plain:
x: int
@dataclass(frozen=True) # eq=True, frozen=True
class Frozen:
x: int
@dataclass(eq=False)
class NoEq:
x: int
Plain.__hash__ # None -> unhashable!
{Plain(1)} # TypeError: unhashable type: 'Plain'
Frozen.__hash__ # generated from the fields
NoEq.__hash__ # inherited from object (identity)
A default @dataclass is unhashable — it cannot be a dict key or set member. That is deliberate (a mutable value-equal object makes a treacherous key), but it surprises people who reach for a dataclass as a lightweight record. Want value-based hashing? Use frozen=True. Note the third case too: eq=False keeps identity hashing, so two field-identical instances land in different buckets.
And when a frozen class needs a derived field, plain assignment in __post_init__ will raise — go through object.__setattr__:
@dataclass(frozen=True)
class Slug:
raw: str
upper: str = field(init=False)
def __post_init__(self):
object.__setattr__(self, "upper", self.raw.upper())
Slug("hi") # Slug(raw='hi', upper='HI')
slots=True builds a different class object
slots=True (3.10+) cuts memory and speeds up attribute access, but __slots__ must be set before class creation — so the decorator creates and returns a brand-new class. Anything that captured the original object is now looking at a ghost:
registry = []
def track(cls):
registry.append(cls)
return cls
@dataclass(slots=True)
@track # runs first, sees the pre-slots class
class Job:
x: int = 0
registry[0] is Job # False
That pattern breaks plugin registries, isinstance checks against a stashed reference, and pickles of the old class. Put @dataclass(slots=True) innermost (or register by name) when you stack decorators. Also note the class-attribute default disappears again, since the name is now a slot descriptor:
@dataclass(slots=True)
class Slotted:
name: str = "anon"
Slotted.name # <member 'name' of 'Slotted' objects>
Good news: the old zero-arg super() breakage in slotted dataclasses is fixed — inheritance and super().method() behave normally on current CPython (verified on 3.13).
asdict() is a recursive deep copy
asdict() looks like a cheap view. It is not: it recurses into nested dataclasses, converts them to plain dicts, and copy.deepcopys everything else.
from dataclasses import asdict
o = Outer() # Outer(inner=Inner(vals=[1, 2]))
d = asdict(o)
d["inner"]["vals"].append(99)
o.inner.vals # [1, 2] <- original untouched
type(d["inner"]).__name__ # 'dict' <- Inner is gone
The isolation is welcome; the cost is not, if you call it per request on a large tree. When you only need a shallow mapping, build it yourself from fields(); when you need speed, consider dataclasses.replace() or a serializer that streams. Also remember asdict() will choke on values deepcopy can’t handle — open sockets, file handles, DB connections.
Cheat sheet
- Any non-scalar default →
field(default_factory=...). Don’t rely on theValueError; it misses hashable-but-mutable objects. - Need to introspect defaults? Use
dataclasses.fields(), notCls.attr—default_factoryfields have no class attribute. - Use
kw_only=True(class-wide) for anything inheritable, and field-ordering errors disappear. frozen=Truefreezes references, not targets. Store tuples /MappingProxyTypefor real immutability, and useobject.__setattr__in__post_init__.- Plain dataclasses are unhashable.
frozen=Truefor value hashing;eq=Falsekeeps identity hashing. field(compare=False)keeps volatile fields (timestamps, cache metadata) out of__eq__.slots=Truereturns a new class — keep it innermost in a decorator stack.asdict()deep-copies the whole tree; it is not free and not lossless.
None of these are bugs. They are the visible seams of a decorator that writes ordinary Python for you — and once you can predict the code it writes, the surprises stop.