Reading history

Python Dataclasses: @dataclass, field, frozen and order

4 min read 0 views

Learn Python dataclasses: generated __init__, __repr__ and __eq__, default_factory, frozen and ordered dataclasses, __post_init__, replace and asdict.

Many classes exist mainly to hold data: a student, an order, a point. Writing __init__, __repr__ and __eq__ for each one is repetitive. The @dataclass decorator, available since Python 3.7, generates these methods from a list of typed fields, so a complete data class takes just a few lines. This lesson covers defaults, mutable fields, frozen and ordered dataclasses, and validation.

In this lesson you will learn

  • Declaring a dataclass with typed fields
  • What @dataclass generates for you
  • Default values and field(default_factory=list)
  • Frozen (immutable) and ordered dataclasses
  • __post_init__, replace() and asdict()

This lesson builds on Classes and Objects and Type Hints.

A First Dataclass

from dataclasses import dataclass, field

@dataclass
class Student:
    name: str
    dept: str
    cgpa: float = 0.0
    courses: list[str] = field(default_factory=list)   # a new list for each object

    def is_honours(self) -> bool:
        return self.cgpa >= 3.75

s1 = Student("Nusrat", "CSE", 3.82)
s2 = Student("Nusrat", "CSE", 3.82)
s3 = Student("Rafi", "EEE")
s3.courses.append("Circuits")

print(s1)                          # generated __repr__
print(s1 == s2, s1 is s2)          # generated __eq__
print(s3, s1.is_honours(), s3.is_honours())

Output

Student(name='Nusrat', dept='CSE', cgpa=3.82, courses=[])
True False
Student(name='Rafi', dept='EEE', cgpa=0.0, courses=['Circuits']) True False
  • Each annotated class variable becomes a field. @dataclass writes an __init__ that takes the fields in order, a readable __repr__, and an __eq__ that compares field values.
  • s1 == s2 is true because their fields match, although they are different objects (s1 is s2 is false).
  • Fields with defaults, like cgpa: float = 0.0, must come after fields without defaults.
  • A list cannot be a plain default, because every object would share it (the same trap as mutable default arguments). field(default_factory=list) creates a fresh list for each object.
  • Dataclasses are normal classes, so you can add methods such as is_honours.

Frozen, Ordered and Validated Dataclasses

from dataclasses import dataclass, field, asdict, replace

@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int
    patch: int = 0

    def __str__(self) -> str:
        return f"{self.major}.{self.minor}.{self.patch}"

v = [Version(1, 10), Version(1, 2, 5), Version(2, 0)]
print([str(x) for x in sorted(v)])           # order=True compares fields in order
print(Version(1, 2) < Version(1, 10))

try:
    v[0].major = 9                           # frozen: fields cannot change
except Exception as e:
    print(type(e).__name__)

print(replace(v[0], patch=1))                # copy with one field changed
print({Version(1, 0): "first"})              # frozen dataclasses are hashable

@dataclass
class Order:
    item: str
    qty: int
    price: float
    total: float = field(init=False)

    def __post_init__(self):                 # runs after the generated __init__
        if self.qty <= 0:
            raise ValueError("qty must be positive")
        self.total = self.qty * self.price

o = Order("notebook", 3, 45.5)
print(o, asdict(o))

Output

['1.2.5', '1.10.0', '2.0.0']
True
FrozenInstanceError
1.10.1
{Version(major=1, minor=0, patch=0): 'first'}
Order(item='notebook', qty=3, price=45.5, total=136.5) {'item': 'notebook', 'qty': 3, 'price': 45.5, 'total': 136.5}
  • order=True generates <, > and friends, comparing fields in the order they are declared, like tuples. So version 1.2.5 sorts before 1.10.0, which plain string sorting would get wrong.
  • frozen=True makes objects immutable: assigning a field raises FrozenInstanceError. Frozen dataclasses are also hashable, so they can be dictionary keys and set members.
  • replace(obj, field=value) returns a modified copy, the usual way to “change” a frozen object.
  • __post_init__ runs right after the generated __init__. Use it for validation and for calculated fields marked field(init=False).
  • asdict() converts a dataclass to a dictionary, ready for JSON.

Dataclass vs Alternatives

Regular classnamedtupledataclass
BoilerplateWrite everythingNoneVery little
MutableYesNoYes, or frozen
Defaults and methodsYesLimitedYes
Type hints requiredNoNoYes
Behaves like a tupleNoYesNo

Common Mistakes

  1. Using courses: list = []; Python raises ValueError. Use field(default_factory=list).
  2. Forgetting the type annotation; name = "x" without a type is a class attribute, not a field.
  3. Placing a field without a default after one with a default, which is a TypeError.
  4. Expecting type hints to be enforced; validate in __post_init__ if needed.

Practice Exercises

Exercise 1. Create a dataclass Book with title, author and a default pages of 100, and print an instance.

Show answer
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    author: str
    pages: int = 100

print(Book("Padma Nadir Majhi", "Manik Bandopadhyay"))

Exercise 2. Make a frozen dataclass Money(amount: int, currency: str) that rejects negative amounts.

Show answer
@dataclass(frozen=True)
class Money:
    amount: int
    currency: str = "BDT"

    def __post_init__(self):
        if self.amount < 0:
            raise ValueError("amount cannot be negative")

Frequently Asked Questions

Can dataclasses use inheritance?

Yes. A dataclass can inherit from another, and the child’s fields are added after the parent’s. The rule about defaults still applies across both.

What does slots=True do?

@dataclass(slots=True) (Python 3.10+) stores fields in fixed slots instead of a per-object dictionary, which saves memory and prevents adding new attributes by mistake.

Summary

  • @dataclass generates __init__, __repr__ and __eq__ from typed fields.
  • Use field(default_factory=...) for list and dict defaults.
  • frozen=True makes objects immutable and hashable; order=True adds comparisons.
  • Validate and compute fields in __post_init__.

Next: Python Context Managers.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *