Skip to content
Python

Python dataclasses: Write Classes With Less Code

Ihsan Ullah · 13 min read
Python dataclasses, Lesson 42 of the Python course: @dataclass, defaults, field() and frozen

Python course · Module 8: OOP in Python · Lesson 42 of 63

Quick answer: A Python dataclass is a normal class with the @dataclass decorator from the dataclasses module. You list the fields with type hints, such as name: str and price: float, and Python writes __init__(), __repr__() and __eq__() for you. Use field(default_factory=list) for list defaults, __post_init__() to check values, and frozen=True for objects that must not change.

In this lesson you will learn:

  • how @dataclass writes __init__, __repr__ and __eq__ from your fields
  • how defaults work, and why a list default needs field(default_factory=list)
  • how to check values in __post_init__()
  • how frozen=True, order=True and replace() work
  • how to turn a dataclass into a dictionary and JSON with asdict()

Before you start: finish Lesson 41, Python Dunder Methods: Make Your Objects Work Like Built-ins. You need classes, __init__ and self from Lesson 38. All examples were run on Linux with Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org.

Why Python dataclasses?

Many classes only hold data. Here is a Product for our shop, written by hand. To print it nicely and compare two products, we need three special methods:

class Product:
    def __init__(self, name, price, quantity=1):
        self.name = name
        self.price = price
        self.quantity = quantity

    def __repr__(self):
        return (f"Product(name={self.name!r}, price={self.price!r}, "
                f"quantity={self.quantity!r})")

    def __eq__(self, other):
        return (self.name, self.price, self.quantity) == (
            other.name, other.price, other.quantity)


pen = Product("pen", 1.5, 4)
print(pen)
print(pen == Product("pen", 1.5, 4))
Product(name='pen', price=1.5, quantity=4)
True

It works, but look at the cost: the names name, price and quantity are typed again and again, in __init__, __repr__ and __eq__. If you add a new attribute later, you must remember to change all three methods. This kind of repeated code is called boilerplate.

The dataclasses documentation says the module provides “a decorator and functions for automatically adding generated special methods such as __init__() and __repr__() to user-defined classes”. PEP 557, which added dataclasses in Python 3.7, puts it simply: “Data Classes save you from writing and maintaining these methods.”

Your first dataclass

Here is the same Product as a dataclass:

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1


pen = Product("pen", 1.5, 4)
notebook = Product("notebook", 3.0)
print(pen)
print(notebook)
print(pen == Product("pen", 1.5, 4))
print(pen == notebook)

pen.quantity = 6
print(pen.quantity, pen.price * pen.quantity)
Product(name='pen', price=1.5, quantity=4)
Product(name='notebook', price=3.0, quantity=1)
True
False
6 9.0
  • @dataclass goes on the line above class. It is a decorator: it takes the class and adds methods to it. (Decorators get their own lesson later in the course.)
  • Each line like name: str is a field. The docs define it: “A field is defined as a class variable that has a type annotation.”
  • quantity: int = 1 gives a default value, so Product("notebook", 3.0) works with two arguments.
  • print(pen) uses the generated __repr__: class name, then each field with its value.
  • == uses the generated __eq__, which compares the fields in order. Two products with the same values are equal.
  • A dataclass is still a normal class. You can change attributes, as with pen.quantity = 6.

The first two lines of output are the same as in step 1, but the class is 5 lines long, decorator included, instead of 13.

Python dataclasses diagram from Lesson 42: five lines with @dataclass and three typed fields produce a generated __init__ with the signature (self, name: str, price: float, quantity: int = 1), a __repr__ printing Product(name='pen', price=1.5, quantity=4), and an __eq__ that compares the fields in order.
You write the fields; @dataclass writes __init__, __repr__ and __eq__ from them.

What @dataclass writes for you

You cannot see the generated methods in your file, but you can ask Python about them:

import inspect
from dataclasses import dataclass, fields


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1


print(inspect.signature(Product.__init__))
print([f.name for f in fields(Product)])

bag = Product(name="bag", price=20.0)
print(bag)

odd = Product("ruler", "cheap", "two")
print(odd)
(self, name: str, price: float, quantity: int = 1) -> None
['name', 'price', 'quantity']
Product(name='bag', price=20.0, quantity=1)
Product(name='ruler', price='cheap', quantity='two')
  • inspect.signature() shows the generated __init__: the parameters are the fields, in the order you wrote them, with the default.
  • fields() from the dataclasses module lists the fields.
  • Keyword arguments work too, as in Lesson 23: Product(name="bag", price=20.0).
  • The last line shows something important: the types are not checked. "cheap" is not a float, but Python accepted it. The docs say: “With two exceptions described below, nothing in @dataclass examines the type specified in the variable annotation.” Type hints are for you, your editor and type checkers. Lesson 48 covers type checkers.

Add methods to a dataclass

You write your own methods in a dataclass exactly as in Lesson 38. @dataclass only adds the methods you did not write:

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1

    def subtotal(self):
        return self.price * self.quantity

    def add(self, more):
        self.quantity += more


pen = Product("pen", 1.5, 4)
pen.add(2)
print(pen)
print(pen.subtotal())
Product(name='pen', price=1.5, quantity=6)
9.0

add() changes the quantity from 4 to 6, and subtotal() returns 6 × 1.5 = 9.0.

Default values: the list trap and default_factory

A shopping cart needs a list of products. The natural idea is items: list = [], but dataclasses refuse it:

from dataclasses import dataclass

try:
    @dataclass
    class ShoppingCart:
        owner: str
        items: list = []
except ValueError as err:
    print("ValueError:", err)
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory

This is a safety check. One [] written in the class would be shared by every cart, which is the shared list trap from Lesson 38 and the mutable default trap from Lesson 23. The docs explain that @dataclass “will raise a ValueError if it detects an unhashable default parameter”, because unhashable values like lists, dicts and sets can change.

The fix is field(default_factory=list). A default factory is a function with no arguments that runs every time a new object needs a default. list is such a function: list() returns a new empty list.

from dataclasses import dataclass, field


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1

    def subtotal(self):
        return self.price * self.quantity


@dataclass
class ShoppingCart:
    owner: str
    items: list[Product] = field(default_factory=list)

    def add(self, product):
        self.items.append(product)

    def total(self):
        return sum(item.subtotal() for item in self.items)


amna = ShoppingCart("Amna")
bilal = ShoppingCart("Bilal")
amna.add(Product("pen", 1.5, 6))
amna.add(Product("notebook", 3.0))
print(amna)
print(bilal)
print(amna.total())
print(amna.items is bilal.items)
ShoppingCart(owner='Amna', items=[Product(name='pen', price=1.5, quantity=6), Product(name='notebook', price=3.0, quantity=1)])
ShoppingCart(owner='Bilal', items=[])
12.0
False
  • Amna’s cart has two products and Bilal’s cart is empty, so each cart got its own list.
  • amna.items is bilal.items is False: two different lists.
  • list[Product] is only a type hint that says “a list of Product objects”.
  • The cart’s repr shows the products inside it, because each product has its own generated __repr__.
  • total() adds 6 × 1.5 + 1 × 3.0 = 12.0.

__post_init__: check and clean values

The generated __init__ only stores the values. To check or change them, write a method called __post_init__. The docs say it “will be called by the generated __init__()“, after the fields are set:

from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1

    def __post_init__(self):
        self.name = self.name.strip().lower()
        if self.price < 0:
            raise ValueError(f"price cannot be negative: {self.price}")
        if self.quantity < 1:
            raise ValueError(f"quantity must be at least 1, got {self.quantity}")


print(Product("  Pen ", 1.5, 4))

try:
    Product("bag", -20.0)
except ValueError as err:
    print("Error:", err)
Product(name='pen', price=1.5, quantity=4)
Error: price cannot be negative: -20.0
  • " Pen " was cleaned to "pen" with strip() and lower().
  • A negative price raised ValueError, so no broken product was created. Raising errors is from Lesson 36.

frozen, order and replace()

You can pass options to the decorator. Our shop’s discount coupons should never change after they are made:

from dataclasses import dataclass, replace, FrozenInstanceError


@dataclass(frozen=True, order=True)
class Coupon:
    percent: int
    code: str


small = Coupon(10, "WELCOME10")
big = Coupon(25, "EID25")

try:
    small.percent = 90
except FrozenInstanceError as err:
    print("FrozenInstanceError:", err)

bigger = replace(big, percent=30)
print(big)
print(bigger)

print(small < big)
print(sorted([big, bigger, small]))
print(len({small, Coupon(10, "WELCOME10"), big}))
FrozenInstanceError: cannot assign to field 'percent'
Coupon(percent=25, code='EID25')
Coupon(percent=30, code='EID25')
True
[Coupon(percent=10, code='WELCOME10'), Coupon(percent=25, code='EID25'), Coupon(percent=30, code='EID25')]
2
  • frozen=True makes the object read-only. The docs say “assigning to fields will generate an exception”. That exception is FrozenInstanceError, a subclass of AttributeError.
  • To “change” a frozen object, make a new one with replace(). bigger is a new coupon with 30 percent; big is unchanged.
  • order=True adds <, <=, > and >=. The docs say they compare “as if it were a tuple of its fields, in order”. percent is the first field, so sorted() orders the coupons by percent, just as tuples are sorted item by item in Lesson 25.
  • A frozen dataclass is hashable, so it can go into a set. The two WELCOME10 coupons are equal, so the set keeps only one of them, and its length is 2.

A normal (not frozen) dataclass cannot go into a set. The docs explain that with the default settings __hash__() “will be set to None, marking it unhashable (which it is, since it is mutable)”.

asdict(): from dataclass to dictionary and JSON

asdict() turns a dataclass into a dictionary, and it also converts the dataclasses inside lists. That dictionary can go straight to json.dumps() from Lesson 34:

import json
from dataclasses import dataclass, field, asdict


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1


@dataclass
class ShoppingCart:
    owner: str
    items: list[Product] = field(default_factory=list)


cart = ShoppingCart("Amna", [Product("pen", 1.5, 6), Product("notebook", 3.0)])

try:
    json.dumps(cart)
except TypeError as err:
    print("TypeError:", err)

data = asdict(cart)
print(data)
print(json.dumps(data, indent=2))
TypeError: Object of type ShoppingCart is not JSON serializable
{'owner': 'Amna', 'items': [{'name': 'pen', 'price': 1.5, 'quantity': 6}, {'name': 'notebook', 'price': 3.0, 'quantity': 1}]}
{
  "owner": "Amna",
  "items": [
    {
      "name": "pen",
      "price": 1.5,
      "quantity": 6
    },
    {
      "name": "notebook",
      "price": 3.0,
      "quantity": 1
    }
  ]
}

json.dumps(cart) on its own fails with TypeError, because the json module does not know dataclasses. asdict() makes plain dicts and lists, which it does know. The docs say dataclasses, dicts, lists and tuples are among the values “recursed into”, which is why the two products inside the list became dicts too.

Try it yourself

Exercise 1: A Customer dataclass

Write a Customer dataclass with name, email and points (default 0). Create Amna with no points and Bilal with 120 points. Give Amna 50 points, print both customers, and check with == that Amna now equals a new Customer("Amna", "amna@example.com", 50).

Exercise 2: Fix the order

This class fails when Python reads it. Fix it, then add add_line(name, price) and total(), and show that two orders do not share their lines:

from dataclasses import dataclass


@dataclass
class Order:
    number: int
    lines: list = []

Exercise 3: A safe coupon

Write a frozen Coupon dataclass with code and percent. In __post_init__, raise ValueError if percent is not between 1 and 90. Use replace() to make a 30 percent copy, then try to make a 95 percent copy.

Solutions

Solution 1

from dataclasses import dataclass


@dataclass
class Customer:
    name: str
    email: str
    points: int = 0


amna = Customer("Amna", "amna@example.com")
bilal = Customer("Bilal", "bilal@example.com", 120)
amna.points += 50
print(amna)
print(bilal)
print(amna == Customer("Amna", "amna@example.com", 50))
Customer(name='Amna', email='amna@example.com', points=50)
Customer(name='Bilal', email='bilal@example.com', points=120)
True

points: int = 0 is a default, and the generated __eq__ compares all three fields.

Solution 2

from dataclasses import dataclass, field


@dataclass
class Order:
    number: int
    lines: list = field(default_factory=list)

    def add_line(self, name, price):
        self.lines.append((name, price))

    def total(self):
        return sum(price for name, price in self.lines)


first = Order(1)
second = Order(2)
first.add_line("pen", 1.5)
first.add_line("bag", 20.0)
print(first)
print(second)
print(first.total())
Order(number=1, lines=[('pen', 1.5), ('bag', 20.0)])
Order(number=2, lines=[])
21.5

field(default_factory=list) gives every order its own new list, so order 2 stays empty.

Solution 3

from dataclasses import dataclass, replace


@dataclass(frozen=True)
class Coupon:
    code: str
    percent: int

    def __post_init__(self):
        if not 1 <= self.percent <= 90:
            raise ValueError(f"percent must be 1 to 90, got {self.percent}")


eid = Coupon("EID20", 20)
print(eid)
print(replace(eid, code="EID30", percent=30))

try:
    replace(eid, percent=95)
except ValueError as err:
    print("Error:", err)
Coupon(code='EID20', percent=20)
Coupon(code='EID30', percent=30)
Error: percent must be 1 to 90, got 95

replace() creates the new object through __init__, so __post_init__ checks the copy too; the docs confirm “__post_init__(), if present, is also called”.

Common mistakes

  • Forgetting the type hint. price = 0.0 without : float is a class attribute, not a field, so it is not in __init__: TypeError: Product.__init__() takes 2 positional arguments but 3 were given.
  • A field without a default after a field with a default. The class itself fails: TypeError: non-default argument 'price' follows default argument 'quantity'. Put fields with defaults last.
  • Using [] or {} as a default. You get ValueError: mutable default <class 'list'> for field lines is not allowed: use default_factory. Use field(default_factory=list), with list and no brackets: field(default_factory=list()) passes a list, not a function, and creating a cart then fails with TypeError: 'list' object is not callable.
  • Changing a frozen object. eid.percent = 50 gives dataclasses.FrozenInstanceError: cannot assign to field 'percent'. Use replace() to make a changed copy.
  • Misspelling __post_init__. With __postinit__ there is no error at all: Python simply never calls it. Our test printed Product(name='bag', price=-20.0), so the price check never ran.

Frequently asked questions

What is the difference between a dataclass and a normal class?

There is no special kind of object. The docs say “The decorator returns the same class that it is called on; no new class is created.” @dataclass only adds methods like __init__, __repr__ and __eq__, which you would otherwise write by hand.

Does a Python dataclass check types?

No. Product("ruler", "cheap", "two") worked in our test. Type hints in a dataclass name the fields and document them, and tools such as mypy can check them, but Python does not check them when the program runs. Check important values yourself in __post_init__.

When should I use a dataclass?

Use one when a class mainly holds data: products, orders, settings, rows from a file. PEP 557 says dataclasses “can be thought of as ‘mutable namedtuples with defaults'”. If the class is mostly behaviour with little data, a normal class is fine.

Summary

  • @dataclass reads the fields (class variables with type hints) and writes __init__, __repr__ and __eq__ for you.
  • Fields with defaults go last; list, dict and set defaults need field(default_factory=...).
  • __post_init__ runs after the generated __init__, so use it to check and clean values.
  • frozen=True makes objects read-only and hashable, order=True adds < and >, and replace() makes a changed copy.
  • asdict() turns a dataclass into a dict, ready for json.dumps(). Types in the hints are not checked at run time.

Next lesson

Next: Lesson 43, Python Composition, ABCs and Protocols: Designing Classes.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

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