Python

Python dataclasses — Fields, Defaults, and Equality

A class that mostly holds data needs the same boilerplate every time: an init that stores each argument, a repr that shows the values, and an equality test that compares them. The dataclass decorator in the standard library writes those methods from the annotated fields you declare, so the class body holds the field list and any real behavior. This guide builds a data class one piece at a time: the generated methods first, then defaults, ordering, frozen instances, a computed field, conversion helpers, and the three errors a first dataclass usually meets. Each step is a small working program with the exact output it prints.

Written November 13, 2026 · Tested with Python 3.12.3 · 6 min read

By the end of this guide
  • The main program: fields in, methods out
  • Defaults, and the factory for a list
  • Ordering: compare and sort by the fields
  • Frozen instances: no assignment, and a hash

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

A field is a class variable with a type annotation. The dataclass decorator reads the fields in the order they are written and generates methods from them: an init that takes one argument per field, a repr that names the class and each field value, and an equality test that compares two instances field by field. Methods you write yourself, such as a total cost calculation, stay in the class and work as usual. The annotations name the fields and their order; with two exceptions covered below, the decorator does not check that a value matches its annotation. A dataclass is the right tool when a class is mainly a record with a little behavior. A class whose work is mostly behavior gains little from it.

The main program: fields in, methods out

The class below declares three fields. The third carries a default, so an instance can omit it. No init, repr, or equality method is written, yet all three work:

Python
from dataclasses import dataclass

@dataclass
class Item:
    name: str
    unit_price: float
    quantity: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity

a = Item("widget", 3.0, 10)
b = Item("widget", 3.0, 10)
c = Item("gadget", 5.0)
print(a)
print(a.name, a.unit_price, a.quantity)
print(c.quantity)
print(a == b)
print(a == c)
print(a.total_cost())

The exact output:

Output
Item(name='widget', unit_price=3.0, quantity=10)
widget 3.0 10
0
True
False
30.0

The repr shows the class name and every field, in field order. The gadget instance took the default quantity of 0 because the call passed no third argument. The two widget instances compare equal because every field matches; equality between instances of different types is always false, even when the field values look the same. Field order is argument order, so the fields are also the init signature: name first, then unit_price, then quantity.

Defaults, and the factory for a list

A plain default suits a value that never changes, such as a number or a string. A list, dict, or set default is different: one object would be shared by every instance that omitted it. The decorator refuses that form, and the field function takes a default_factory instead. The factory is a callable with no arguments, called fresh for each new instance:

Python
from dataclasses import dataclass, field

@dataclass
class Cart:
    owner: str
    items: list = field(default_factory=list)
    note: str = "empty"

x = Cart("ana")
y = Cart("bob")
x.items.append("pen")
print(x)
print(y)
print(x.items, y.items)
print(x.items is y.items)

The exact output:

Output
Cart(owner='ana', items=['pen'], note='empty')
Cart(owner='bob', items=[], note='empty')
['pen'] []
False

Appending to the first cart left the second cart empty, and the identity test prints False: each cart holds its own list. The factory runs at instance creation, not at class definition, which is the whole point. The note field shows the plain form next to it in the same class: a field can use either a plain default or a field call, and a field call can also carry a plain default with its default argument when other field options are needed.

Ordering: compare and sort by the fields

Equality comes from the decorator by default. The four ordering comparisons do not. Passing order=True generates them, and the comparison walks the fields in order, as if each instance were a tuple of its field values:

Python
from dataclasses import dataclass

@dataclass(order=True)
class Score:
    points: int
    name: str

scores = [Score(30, "bob"), Score(10, "cy"), Score(30, "ana")]
print(sorted(scores))
print(Score(10, "cy") < Score(30, "ana"))
print(Score(30, "ana") < Score(30, "bob"))
print(max(scores))

The exact output:

Output
[Score(points=10, name='cy'), Score(points=30, name='ana'), Score(points=30, name='bob')]
True
True
Score(points=30, name='bob')

Points decide first because points is the first field. The two 30-point scores fall through to the name field, so ana sorts before bob. That fall-through is the rule to design around: put the field that should decide most comparisons first, and treat the later fields as tie-breakers. A field can opt out of comparisons with field(compare=False) when it should not affect sorting or equality.

Frozen instances: no assignment, and a hash

Passing frozen=True makes assignment to a field raise an exception. A frozen dataclass with equality on also gains a generated hash, built from its field values, so instances can sit in a set or serve as dict keys:

Python
from dataclasses import dataclass, FrozenInstanceError

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

p = Point(1, 2)
print(p)
print(hash(p) == hash(Point(1, 2)))
print(len({p, Point(1, 2), Point(3, 4)}))
try:
    p.x = 9
except FrozenInstanceError as e:
    print(f"FrozenInstanceError: {e}")

The exact output:

Output
Point(x=1, y=2)
True
2
FrozenInstanceError: cannot assign to field 'x'

Two equal points hash the same, so the set holds two entries, not three. A plain mutable dataclass is unhashable by default: it has equality but no hash, because a value that can change after it enters a set would break the set. Freezing is the statement that the values will not change, and the hash is the reward. Frozen blocks assignment to the fields; it does not freeze objects the fields point at, so a frozen instance holding a list can still see that list change.

A computed field with post_init

Some fields are worked out from the others instead of passed in. Mark such a field with field(init=False) so the generated init skips it, then set it in a post_init method, which the generated init calls at the end:

Python
from dataclasses import dataclass, field

@dataclass
class Rectangle:
    width: float
    height: float
    area: float = field(init=False)

    def __post_init__(self):
        self.area = self.width * self.height

r = Rectangle(3.0, 4.0)
print(r)
print(r.area)

The exact output:

Output
Rectangle(width=3.0, height=4.0, area=12.0)
12.0

The caller passes only width and height. The area still appears in the repr, because init=False removes a field from the init alone, not from the repr or equality. The same hook serves for validation: a post_init that raises on a bad combination stops the instance from being built at all, at the moment the bad values arrive.

Convert and copy: asdict, astuple, replace

Three helper functions work on any dataclass instance. The asdict function returns a dict of field names to values, astuple returns the values as a tuple, and replace builds a new instance with named fields changed:

Python
from dataclasses import dataclass, asdict, astuple, replace

@dataclass
class Item:
    name: str
    unit_price: float
    quantity: int = 0

a = Item("widget", 3.0, 10)
print(asdict(a))
print(astuple(a))
b = replace(a, quantity=4)
print(b)
print(a.quantity, b.quantity)

The exact output:

Output
{'name': 'widget', 'unit_price': 3.0, 'quantity': 10}
('widget', 3.0, 10)
Item(name='widget', unit_price=3.0, quantity=4)
10 4

The original still holds quantity 10 after the replace; the copy is a separate instance. Both converters go deep: a field whose value is itself a dataclass, a list, a dict, or a tuple is converted piece by piece, and other values are copied with the copy module. That makes asdict the natural first step when an instance needs to become data for another tool, such as JSON text.

Three errors a first dataclass meets

A field with no default is a required argument, and omitting it raises the same TypeError a missing function argument raises. The other two errors arrive at class definition, before any instance exists: a mutable default is refused with a pointer to the fix, and a field without a default cannot follow a field that has one:

Python
from dataclasses import dataclass

@dataclass
class Item:
    name: str
    quantity: int = 0

try:
    Item()
except TypeError as e:
    print(f"TypeError: {e}")
try:
    @dataclass
    class Bad:
        items: list = []
except ValueError as e:
    print(f"ValueError: {e}")
try:
    @dataclass
    class BadOrder:
        a: int = 1
        b: int
except TypeError as e:
    print(f"TypeError: {e}")

The exact output:

Output
TypeError: Item.__init__() missing 1 required positional argument: 'name'
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory
TypeError: non-default argument 'b' follows default argument

The field-order error is the generated init showing through: an init cannot place a required parameter after a defaulted one, so the class cannot either. The fix is to reorder the fields, or give the later field a default too. The mutable-default error names its own fix: default_factory, as in the cart example above. Both errors fire while the class is being defined, so a program that imports cleanly has already passed them.

Which form for which job

Job Form Why
A record class with a little behavior The dataclass decorator on annotated fields Init, repr, and equality are generated from the field list
An optional field A plain default on the field The init argument can be omitted, in field order
A list, dict, or set that starts empty field with default_factory Each instance gets a fresh object, never a shared one
Sorting or comparing instances The order=True decorator argument Comparisons walk the fields in order, later fields break ties
An instance that must not change The frozen=True decorator argument Assignment raises, and the instance gains a hash
A value derived from other fields field(init=False) plus post_init The caller never passes it, and it is set before the init returns
An instance as plain data asdict or astuple Nested dataclasses, lists, and dicts are converted too
A changed copy of an instance replace with the fields to change The original stays as it was

Checklist

  • Before adding a list, dict, or set field, give it a default_factory; a plain mutable default stops the class from being defined.
  • Before relying on sorting, set order=True and put the deciding field first; later fields only break ties.
  • Before putting instances in a set or using them as dict keys, freeze the class; a mutable dataclass has no hash.
  • Before passing a computed value in by hand, make it an init=False field set in post_init so it cannot disagree with the fields it came from.
  • Before ordering fields with defaults, place every field without a default ahead of every field that has one.
  • Before comparing instances of two different classes for equality, remember the answer is always false, whatever the fields hold.

Sources

  • Python Standard Library, dataclasses — the dataclass decorator and its init, repr, eq, order, and frozen options, the field function with default and default_factory, post_init, and the asdict, astuple, and replace helpers.
  • Python Tutorial, Classes — class definitions, instances, and method objects, the plain class machinery a dataclass is built on.

Keep Exploring