dataclasses — data classes

dataclass fields, default_factory versus mutable defaults, asdict, replace, frozen assignment, and slots limits, checked on Python 3.13.12.

The dataclasses module, added in Python 3.7, generates methods such as __init__ and __repr__ from type-annotated fields. Import dataclass, field, and the helpers from dataclasses. Links point to the Python 3.13 documentation, and the examples were checked on Python 3.13.12.

This page covers the decorator and helpers used most often: illegal mutable defaults versus default_factory, asdict, astuple, replace, frozen assignment, and slots. It does not reteach the copy module. Official documentation states that asdict and astuple recurse into nested dataclasses, dicts, lists, and tuples, and copy other objects with copy.deepcopy().

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Fields, defaults, and conversion

A field is a class variable with a type annotation. Use dataclasses.field when the default must be created by a factory, or when you need to omit a field from __init__, __repr__, or comparison. fields(class_or_instance) returns the field definitions. is_dataclass is true for both the class and its instances.

Official documentation raises ValueError if it detects an unhashable default parameter, on the assumption that unhashable values are mutable. Since Python 3.11 this check uses unhashability rather than a fixed list of list, dict, and set. A shared list default such as items: list = [] is rejected; field(default_factory=list) calls list() for each new instance.

dataclasses.dataclass, dataclasses.field, dataclasses.fields, dataclasses.is_dataclass, dataclasses.asdict, dataclasses.astuple, dataclasses.replace

@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)
dataclasses.field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING)
dataclasses.fields(class_or_instance)
dataclasses.is_dataclass(obj)
dataclasses.asdict(obj, *, dict_factory=dict)
dataclasses.astuple(obj, *, tuple_factory=tuple)
dataclasses.replace(obj, /, **changes)

Declare fields, give each instance its own mutable default, and convert or copy a dataclass instance.

ParameterDescription
default_factoryA zero-argument callable used when a default value is needed. Do not pass both default and default_factory.
obj / changesasdict, astuple, and replace require a dataclass instance. replace accepts field=value replacements.

Returns: fields returns a tuple of Field objects. is_dataclass returns a bool. asdict returns a dict. astuple returns a tuple. replace returns a new instance of the same type.

Raises

  • ValueError — Raised at class-decoration time for an unhashable field default such as a list. Also raised if replace is asked to change an init=False field.
  • TypeError — asdict, astuple, and replace raise TypeError when obj is not a dataclass instance. replace also raises TypeError for unknown field names.
  • asdict and astuple recurse into dataclasses, dicts, lists, and tuples. Other objects are copied with copy.deepcopy(). For a shallow mapping of fields, official documentation shows a comprehension over fields(obj).
  • replace calls the dataclass __init__, so __post_init__ runs on the new instance.
python
from dataclasses import dataclass, field, fields, asdict, astuple, replace, is_dataclass

try:
    @dataclass
    class Bad:
        items: list = []
except ValueError as err:
    print(type(err).__name__)

@dataclass
class Bag:
    items: list = field(default_factory=list)
    label: str = "x"

a = Bag()
b = Bag()
a.items.append(1)
print(a.items, b.items, a.items is not b.items)
print(is_dataclass(Bag), is_dataclass(a), is_dataclass(list))
print(fields(Bag)[0].name, fields(Bag)[0].default_factory is list)
print(asdict(Bag([1, 2], "n")), astuple(Bag([1, 2], "n")))
print(replace(Bag([1], "n"), label="m"))

Expected output

ValueError
[1] [] True
True True False
items True
{'items': [1, 2], 'label': 'n'} ([1, 2], 'n')
Bag(items=[1], label='m')

Related: copy

Official documentation →

Frozen instances and slots

frozen=True makes field assignment and deletion raise FrozenInstanceError, which is a subclass of AttributeError. Official documentation states that it is not possible to create truly immutable Python objects: frozen emulates immutability by blocking assignment, but it is not a deep freeze. Mutating a list stored in a frozen instance still succeeds.

slots=True, added in Python 3.10, generates __slots__ and returns a new class rather than the decorated class object. Instances normally have no __dict__, so assigning an unknown attribute raises AttributeError. If the class already defines __slots__, TypeError is raised. Official warnings also apply: a no-arg super() call in a slots dataclass raises TypeError, and passing parameters to a base __init_subclass__ can raise TypeError. Those two inheritance cases are not run in the example below.

dataclasses.dataclass, dataclasses.FrozenInstanceError, dataclasses.replace

@dataclasses.dataclass(*, frozen=False, slots=False, ...)
exception dataclasses.FrozenInstanceError
dataclasses.replace(obj, /, **changes)

Block field assignment on a frozen instance, and use slots to omit __dict__.

ParameterDescription
frozenIf true, generated __setattr__ and __delattr__ raise FrozenInstanceError. The default is False.
slotsIf true, the decorator generates __slots__ and returns a new class. The default is False.

Returns: replace returns a new instance, including when the class is frozen, uses slots, or both.

Raises

  • FrozenInstanceError — Raised when assigning to or deleting a field on a frozen instance. It is a subclass of AttributeError.
  • AttributeError — Raised when assigning an unknown attribute on a slots instance that has no __dict__.
  • TypeError — Raised if slots=True is combined with an existing __slots__ on the class, and in the official super() and __init_subclass__ warning cases.
  • box.items.append(2) mutates the list in place and does not assign the field, so it does not raise FrozenInstanceError.
  • If the class already defines __setattr__ or __delattr__ and frozen is true, official documentation says TypeError is raised at decoration time.
python
from dataclasses import dataclass, FrozenInstanceError, replace

@dataclass(frozen=True)
class Box:
    items: list
    n: int = 0

box = Box([1])
box.items.append(2)
print(box.items)
try:
    box.n = 1
except FrozenInstanceError as err:
    print(type(err).__name__)

@dataclass(slots=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
print(hasattr(p, "__dict__"), p.x, p.y)
try:
    p.z = 3
except AttributeError as err:
    print(type(err).__name__)

@dataclass(frozen=True, slots=True)
class Cell:
    v: int

print(replace(Cell(1), v=2), hasattr(Cell(1), "__dict__"))

Expected output

[1, 2]
FrozenInstanceError
False 1 2
AttributeError
Cell(v=2) False

Official documentation →