Data Classes & Advanced Class Patterns
Published by Brayan K
Master the powerful @dataclass decorator and advanced class patterns that professional engineers use when building large Python systems. Learn to create efficient, immutable, and production-ready data models used in APIs, ML pipelines, and enterprise architectures.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What @dataclass writes for you
This lesson is about @dataclass, which writes the routine methods of a class that mostly holds data. The other class patterns have lessons of their own: Magic Methods & the Python Data Model, Mixins, Multiple Inheritance & OOP Patterns, Design Patterns in Python (Singleton, Factory, Strategy) and __slots__ & Memory Optimization, which makes each object smaller.
A class in Object-Oriented Programming needed an __init__ to store its values, a __repr__ to print them and an __eq__ to compare them. For a class that is mostly data, @dataclass writes all three from a list of names with type hints, the hints from Type Hints & Static Typing with mypy:
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int
a = Book("Dune", 412)
b = Book("Dune", 412)
print(a)
print(a == b)
print(a is b)
# ✅ Expected output:
# Book(title='Dune', pages=412)
# True
# FalseBook("Dune", 412) works because the class now has an __init__ taking the fields in the order they're written. print() shows the fields by name, and == compares them, so two books with the same title and pages are equal, though is shows they're two objects. For a different type, the generated __eq__ returns NotImplemented, allowing Python to try the other object's comparison. The expression User("Sam") == "Sam" is False, where a hand-written __eq__ that reads other.name stops with AttributeError: 'str' object has no attribute 'name'.
@dataclass is a class decorator, so, as Decorators & Advanced Features showed, it's the same as writing Book = dataclass(Book) after the class.
Only names with a hint become fields, and the hints aren't checked
@dataclass finds the fields in the class's __annotations__, the names with a hint. A name given a value without a hint is an ordinary class attribute, and __init__ doesn't take it:
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages = 0
print(Book("Dune"))
print(Book("Dune", 412))
# ✅ Expected output:
# Book(title='Dune')
# ✅ Expected error:
# TypeError: Book.__init__() takes 2 positional arguments but 3 were givenThe hints only name the fields: as with any hint, Python doesn't check the values. Swap the arguments and the book stores a number as its title:
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int
b = Book(412, "Dune")
print(b)
print(b.pages * 2)
# ✅ Expected output:
# Book(title=412, pages='Dune')
# DuneDunemypy reports both arguments of that call, starting with Argument 1 to "Book" has incompatible type "int"; expected "str". To check values while the program runs, see Data Validation with Pydantic.
Defaults, and why a list can't be one
A field gets a default the way a variable gets a value. Fields with defaults come after the ones without, as parameters do:
from dataclasses import dataclass
@dataclass
class Book:
title: str
pages: int = 0
format: str = "paperback"
print(Book("Dune"))
print(Book("Dune", 412, format="ebook"))
# ✅ Expected output:
# Book(title='Dune', pages=0, format='paperback')
# Book(title='Dune', pages=412, format='ebook')Put a field without a default, author: str, after pages: int = 0, and the class itself stops with a TypeError. Up to Python 3.12, and in this site's Run button, it reads non-default argument 'author' follows default argument; from 3.13 it adds the field before, follows default argument 'pages'.
A list as a default is refused outright. Advanced Functions & Parameters Masterclass showed why: one default list, made once, would be shared by every object. @dataclass stops the class from being made at all:
from dataclasses import dataclass
@dataclass
class Basket:
owner: str
items: list[str] = []
print("never printed")
# ✅ Expected error:
# ValueError: mutable default <class 'list'> for field items is not allowed: use default_factoryfield(default_factory=list) gives the field a function to call instead, so each object gets a new list of its own. A dict or a set works the same way:
from dataclasses import dataclass, field
@dataclass
class Basket:
owner: str
items: list[str] = field(default_factory=list)
ada = Basket("Ada")
bo = Basket("Bo")
ada.items.append("tea")
print(ada)
print(bo)
print(ada.items is bo.items)
# ✅ Expected output:
# Basket(owner='Ada', items=['tea'])
# Basket(owner='Bo', items=[])
# FalseThe factory is the function itself, list, not a call to it. With list() the class is made, and the mistake shows only when an object needs the default:
from dataclasses import dataclass, field
@dataclass
class Basket:
owner: str
items: list[str] = field(default_factory=list())
print("class made")
print(Basket("Ada"))
# ✅ Expected output:
# class made
# ✅ Expected error:
# TypeError: 'list' object is not callable__post_init__ checks the values once, when the object is made
The written __init__ calls a method named __post_init__ at its end, if the class has one. That's the place to check the values:
from dataclasses import dataclass
@dataclass
class Account:
owner: str
balance: float = 0.0
def __post_init__(self):
if self.balance < 0:
raise ValueError("balance can't be negative")
print(Account("Ada", 10))
print(Account("Bo", -5))
# ✅ Expected output:
# Account(owner='Ada', balance=10)
# ✅ Expected error:
# ValueError: balance can't be negativeIt runs once. Nothing checks a value assigned later:
from dataclasses import dataclass
@dataclass
class Account:
owner: str
balance: float = 0.0
def __post_init__(self):
if self.balance < 0:
raise ValueError("balance can't be negative")
acct = Account("Ada", 10)
acct.balance = -50
print(acct)
# ✅ Expected output:
# Account(owner='Ada', balance=-50)A field worked out from the others, marked field(init=False) so that __init__ doesn't take it, has the same limit: it goes stale when they change. A property, from Properties & Descriptors, works the value out each time instead.
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, 4)
print(r)
r.width = 10
print(r)
# ✅ Expected output:
# Rectangle(width=3, height=4, area=12)
# Rectangle(width=10, height=4, area=12)A dataclass can inherit fields
Inheritance and Polymorphism said classes mostly made of data can inherit too. A child dataclass takes its parent's fields first, then its own, so its __init__ needs no super().__init__():
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float
@dataclass
class Book(Item):
author: str
b = Book("Dune", 9.99, "Herbert")
print(b)
print(isinstance(b, Item))
# ✅ Expected output:
# Book(name='Dune', price=9.99, author='Herbert')
# TrueThe order rule still applies across the two classes: a parent field with a default followed by a child field without one stops with the same TypeError as above. kw_only=True on the child fixes it, because a field passed by name has no place in the order:
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float = 0.0
@dataclass(kw_only=True)
class Book(Item):
author: str
print(Book("Dune", 9.99, author="Herbert"))
print(Book("Notes", author="Ada"))
# ✅ Expected output:
# Book(name='Dune', price=9.99, author='Herbert')
# Book(name='Notes', price=0.0, author='Ada')A child's __post_init__ replaces its parent's, as any method does, so the parent's check doesn't run:
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float
def __post_init__(self):
if self.price < 0:
raise ValueError("price can't be negative")
@dataclass
class Book(Item):
author: str
def __post_init__(self):
self.author = self.author.title()
print(Book("Dune", -1.0, "frank herbert"))
# ✅ Expected output:
# Book(name='Dune', price=-1.0, author='Frank Herbert')Calling super().__post_init__() first runs both:
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float
def __post_init__(self):
if self.price < 0:
raise ValueError("price can't be negative")
@dataclass
class Book(Item):
author: str
def __post_init__(self):
super().__post_init__()
self.author = self.author.title()
print(Book("Dune", 9.99, "frank herbert"))
print(Book("Dune", -1.0, "frank herbert"))
# ✅ Expected output:
# Book(name='Dune', price=9.99, author='Frank Herbert')
# ✅ Expected error:
# ValueError: price can't be negativefrozen=True: objects that can't change, and can go in a set
@dataclass(frozen=True) refuses any assignment to a field once the object exists:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
print(p)
p.x = 9
# ✅ Expected output:
# Point(x=1, y=2)
# ✅ Expected error:
# dataclasses.FrozenInstanceError: cannot assign to field 'x'To change one, make a new object with replace(), which copies the others:
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
q = replace(p, x=9)
print(p)
print(q)
# ✅ Expected output:
# Point(x=1, y=2)
# Point(x=9, y=2)Freezing also decides whether an object can be hashed, which a set and a dict's keys need. A plain dataclass compares its fields with == and can still change, so it gets no hash, the same as the Point in Object-Oriented Programming:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
print(Point(1, 2) == Point(1, 2))
print(hash(Point(1, 2)))
# ✅ Expected output:
# True
# ✅ Expected error:
# TypeError: unhashable type: 'Point'Putting it in a set fails the same way. Up to Python 3.13 the message is the one above; 3.14 says cannot use 'Point' as a set element (unhashable type: 'Point'). A frozen dataclass gets a hash from its fields, so equal points count once in a set and work as a dict's keys:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: int
y: int
visited = {Point(1, 2), Point(1, 2), Point(3, 4)}
print(len(visited))
print(Point(1, 2) in visited)
labels = {Point(0, 0): "home"}
print(labels[Point(0, 0)])
# ✅ Expected output:
# 2
# True
# homeFrozen only stops assignments to the fields. A list in a field is still a list, and it can change:
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Team:
name: str
members: list[str] = field(default_factory=list)
reds = Team("Reds")
reds.members.append("Ada")
print(reds)
# ✅ Expected output:
# Team(name='Reds', members=['Ada'])That Team can't be hashed either: hash(reds) stops with TypeError: unhashable type: 'list', since a hash is worked out from every field.
order=True sorts by the fields, in the order they're written
order=True writes <, <=, > and >=. They compare the fields in order, as tuples are compared: the first field, then the second on a tie.
from dataclasses import dataclass
@dataclass(order=True)
class Score:
points: int
player: str
scores = [Score(70, "Bo"), Score(90, "Ada"), Score(70, "Al")]
for s in sorted(scores):
print(s)
print(max(scores).player)
# ✅ Expected output:
# Score(points=70, player='Al')
# Score(points=70, player='Bo')
# Score(points=90, player='Ada')
# AdaWithout it, a dataclass can be compared with == but not sorted:
from dataclasses import dataclass
@dataclass
class Score:
points: int
player: str
scores = [Score(70, "Bo"), Score(90, "Ada")]
print(sorted(scores))
# ✅ Expected error:
# TypeError: '<' not supported between instances of 'Score' and 'Score'To sort by one field, whatever order the fields are in, give sorted() a key, as in Lambda Functions:
from dataclasses import dataclass
@dataclass
class Score:
player: str
points: int
scores = [Score("Bo", 70), Score("Ada", 90), Score("Al", 70)]
for s in sorted(scores, key=lambda s: s.points, reverse=True):
print(s.player, s.points)
# ✅ Expected output:
# Ada 90
# Bo 70
# Al 70To JSON, keyword-only fields, and fields left out
json.dumps(), from Working with JSON, doesn't know a dataclass. asdict() turns one into a dict first, nested dataclasses included:
import json
from dataclasses import dataclass, asdict
@dataclass
class Address:
city: str
postcode: str
@dataclass
class Customer:
name: str
address: Address
c = Customer("Bo", Address("Leeds", "LS1"))
print(asdict(c))
print(json.dumps(asdict(c)))
print(json.dumps(c))
# ✅ Expected output:
# {'name': 'Bo', 'address': {'city': 'Leeds', 'postcode': 'LS1'}}
# {"name": "Bo", "address": {"city": "Leeds", "postcode": "LS1"}}
# ✅ Expected error:
# TypeError: Object of type Customer is not JSON serializablekw_only=True makes every field a keyword argument, which keeps a call with several settings readable:
from dataclasses import dataclass
@dataclass(kw_only=True)
class Config:
host: str
port: int = 8000
secure: bool = False
print(Config(host="localhost", secure=True))
print(Config("localhost", 8000))
# ✅ Expected output:
# Config(host='localhost', port=8000, secure=True)
# ✅ Expected error:
# TypeError: Config.__init__() takes 1 positional argument but 3 were givenfield() can also leave a field out of the printed form, with repr=False, or out of ==, with compare=False:
from dataclasses import dataclass, field
@dataclass
class User:
name: str
password: str = field(repr=False)
logins: int = field(default=0, compare=False)
print(User("ada", "hunter2"))
print(User("ada", "x", 1) == User("ada", "x", 5))
# ✅ Expected output:
# User(name='ada', logins=0)
# TrueFinally, slots=True gives the class __slots__, so its objects have no __dict__. An ordinary dataclass takes a misspelt attribute without a word, as plain classes do; a slotted one refuses it with an AttributeError, whose message 3.13 made longer. What it saves in memory is __slots__ & Memory Optimization 's subject.
from dataclasses import dataclass
@dataclass
class Loose:
x: int
@dataclass(slots=True)
class Tight:
x: int
a = Loose(1)
a.y = 2
print(a, a.y)
print(Tight.__slots__)
print(hasattr(Tight(1), "__dict__"))
# ✅ Expected output:
# Loose(x=1) 2
# ('x',)
# FalsePractice: a basket and a coupon
Give each basket its own list, freeze the coupon, and catch the error a frozen coupon raises. The 👉 comment beside each blank gives its answer if you get stuck.
from dataclasses import dataclass, field, FrozenInstanceError
@dataclass
class Basket:
owner: str
items: list[str] = field(default_factory=___) # 👉 replace ___ with list
def add(self, item: str) -> None:
self.items.append(item)
@dataclass(___=True) # 👉 replace ___ with frozen
class Coupon:
code: str
percent: int
ada = Basket("Ada")
bo = Basket("Bo")
ada.add("tea")
print(ada)
print(bo)
c = Coupon("SAVE10", 10)
print(c == Coupon("SAVE10", 10))
print(len({c, Coupon("SAVE10", 10)}))
try:
c.percent = 50
except ___ as e: # 👉 replace ___ with FrozenInstanceError
print("refused:", e)
# ✅ Expected output:
# Basket(owner='Ada', items=['tea'])
# Basket(owner='Bo', items=[])
# True
# 1
# refused: cannot assign to field 'percent'The program runs, and still mypy reports the line that assigns to the coupon: Property "percent" defined in "Coupon" is read-only. It's right: the line is there to show the error.
On your own: tasks that sort and check themselves
Write a dataclass Task with priority (an int), title (a str) and tags, a list of strings that is new for each task and left out of comparisons. Tasks sort by priority, then title, and making one with a priority outside 1 to 5 raises ValueError("priority must be 1 to 5"). Make Task(3, "Write report"), Task(1, "Fix login") and Task(3, "Book room"), tag the first one "work", and print them sorted, one per line. Then try Task(9, "Someday") and print refused: with the error.
from dataclasses import dataclass, field
# your code herefrom dataclasses import dataclass, field
@dataclass(order=True)
class Task:
priority: int
title: str
tags: list[str] = field(default_factory=list, compare=False)
def __post_init__(self):
if not 1 <= self.priority <= 5:
raise ValueError("priority must be 1 to 5")
tasks = [Task(3, "Write report"), Task(1, "Fix login"), Task(3, "Book room")]
tasks[0].tags.append("work")
for t in sorted(tasks):
print(t)
try:
Task(9, "Someday")
except ValueError as e:
print("refused:", e)
# ✅ Expected output:
# Task(priority=1, title='Fix login', tags=[])
# Task(priority=3, title='Book room', tags=[])
# Task(priority=3, title='Write report', tags=['work'])
# refused: priority must be 1 to 5The two tasks with priority 3 sort by title, and the tags don't take part, since compare=False leaves them out of < as well as ==.
Practice quiz
Basket is a dataclass with owner: str and items: list[str] = []. The program then prints Basket("Ada"). What happens?
- It prints Basket(owner='Ada', items=[])
- It stops with ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory
- It prints Basket(owner='Ada', items=[]), and every Basket shares that list
- It stops with TypeError: Basket.__init__() missing 1 required positional argument: 'items'
Answer: It stops with ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. @dataclass refuses a list as a default when the class is made, before any Basket exists. field(default_factory=list) gives each Basket its own.
In a dataclass Book, title: str has a hint and pages = 0 doesn't. What does print(Book("Dune", 412)) do?
- It prints Book(title='Dune', pages=412)
- It prints Book(title='Dune')
- It prints Book(title='Dune', pages=0)
- It stops with TypeError: Book.__init__() takes 2 positional arguments but 3 were given
Answer: It stops with TypeError: Book.__init__() takes 2 positional arguments but 3 were given. Only names with a hint become fields, so __init__ takes the title alone. pages = 0 is a plain class attribute.
Point is a dataclass with x and y, without frozen=True. What does print(len({Point(1, 2), Point(1, 2)})) do?
- It stops with TypeError, because a Point can't be hashed
- It prints 1
- It prints 2
- It prints 0
Answer: It stops with TypeError, because a Point can't be hashed. A dataclass that compares its fields with == and can still change gets no hash, so it can't go in a set. With frozen=True it can, and the answer would be 1.
Score is @dataclass(order=True) with points, then player. What does print(sorted([Score(70, "Bo"), Score(90, "Ada"), Score(70, "Al")])[0]) print?
- Score(points=70, player='Bo')
- Score(points=90, player='Ada')
- Score(points=70, player='Al')
- It stops with TypeError
Answer: Score(points=70, player='Al'). order=True compares the fields in order, like tuples: points first, and on a tie the player's name, where Al comes before Bo.
Account's __post_init__ refuses a negative balance. After acct = Account("Ada", 10), the program runs acct.balance = -50 and print(acct). What is printed?
- It stops with ValueError: balance can't be negative
- Account(owner='Ada', balance=-50)
- Account(owner='Ada', balance=10)
- It stops with AttributeError
Answer: Account(owner='Ada', balance=-50). __post_init__ runs once, when the object is made. Nothing checks a later assignment.
A Basket dataclass has items: list[str] = field(default_factory=list()). What does print(Basket("Ada")) do?
- It prints Basket(owner='Ada', items=[])
- It stops with ValueError when the class is made
- It prints Basket(owner='Ada', items=None)
- It stops with TypeError: 'list' object is not callable
Answer: It stops with TypeError: 'list' object is not callable. list() is an empty list, made once. default_factory needs the function itself, list, to call for each new Basket.
Team is @dataclass(frozen=True) with name and members: list[str] = field(default_factory=list). After reds = Team("Reds"), the program runs reds.members.append("Ada") and print(reds). What happens?
- It stops with dataclasses.FrozenInstanceError: cannot assign to field 'members'
- It prints Team(name='Reds', members=[])
- It prints Team(name='Reds', members=['Ada'])
- It stops with AttributeError
Answer: It prints Team(name='Reds', members=['Ada']). frozen stops assigning to a field, but the list in the field is an ordinary list that can still change.
Account's balance check is in a method named __postinit__, without the second underscore. What does print(Account("Bo", -5)) print?
- Account(owner='Bo', balance=-5)
- It stops with ValueError: balance can't be negative
- It stops with AttributeError
- It stops with TypeError
Answer: Account(owner='Bo', balance=-5). @dataclass calls a method named exactly __post_init__. The misspelt one is just a method nobody calls.
Continue this course
- Previous: Type Hints & Static Typing with mypy
- Next: Magic Methods & the Python Data Model — Implement __repr__, __len__, __eq__, and more to integrate with Python
- Quick reference: Python cheat sheet › Classes
Frequently asked questions
Can I still write my own __repr__ or __init__?
Yes. @dataclass leaves a method you wrote in place and writes only the others. A Money class with its own __repr__ printed £2.50, and == still compared its fields; a Temperature class with its own __init__(self, fahrenheit) printed Temperature(celsius=100.0) for 212.
How do I turn JSON back into a dataclass?
Customer(**json.loads(text)) fills the fields from the dictionary, but a nested dataclass comes back as a plain dict: Customer(name='Bo', address={'city': 'Leeds'}). Data Validation with Pydantic builds the nested objects for you.
Can a field's default be another dataclass's object?
Not if that instance is unhashable, as an ordinary mutable dataclass usually is. From Python 3.11, @dataclass refuses unhashable defaults, so an ordinary Address dataclass used as address: Address = Address("York") raises ValueError and asks for default_factory. Python 3.10 accepted it and shared one Address between every Customer. field(default_factory=lambda: Address("York")) makes a new one each time. A hashable instance, such as a suitable frozen dataclass, can be a plain shared default.
Should I use a dataclass, a NamedTuple or a dict?
A NamedTuple is a tuple with names for its items, so it can't change and it unpacks like a tuple: namedtuple & NamedTuple teaches it. A dict suits keys you don't know when you write the code. A dataclass suits a fixed set of named fields with methods of their own.
Can a frozen dataclass inherit from a normal one?
No. Python refuses when the class is made, with TypeError: cannot inherit frozen dataclass from a non-frozen one, and the other way round with cannot inherit non-frozen dataclass from a frozen one.
What do astuple() and fields() do?
Both come from the dataclasses module. astuple(Point(1, 2)) gives (1, 2), and fields() lists the fields, so [f.name for f in fields(p)] gives ['x', 'y'].
What is __match_args__?
@dataclass writes it too, so that match can take a dataclass's fields in order: case Point(0, y): matches Point(0, 5) and sets y to 5. Structural Pattern Matching (match/case) teaches match.
How do I make a dataclass that can change hashable?
unsafe_hash=True adds a hash anyway, and the name is a warning: change a field after putting the object in a set, and the set can't find it. After p.x = 5, p in seen printed False. Magic Methods & the Python Data Model explains hashing.
Related lessons
- Mixins, Multiple Inheritance & OOP Patterns
- Design Patterns in Python (Singleton, Factory, Strategy)
- __slots__ & Memory Optimization
- Object-Oriented Programming
- Decorators & Advanced Features
- Data Validation with Pydantic
- Advanced Functions & Parameters Masterclass
- Properties & Descriptors
- Inheritance and Polymorphism
- Lambda Functions
- Working with JSON