PY-101 ยท Object-oriented Python
Dataclasses
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A dataclass is a class mainly for holding data, created with the @dataclass decorator. You list the fields with type hints, and Python writes __init__, __repr__ and __eq__ for you. Options like frozen=True (cannot change) and order=True (can sort) add more with one word.
- Define a @dataclass with typed fields
- Use defaults and field(default_factory=list)
- Use frozen and order
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
from dataclasses import dataclass, field@dataclassclass Product:name: strprice: floatqty: int = 1tags: list[str] = field(default_factory=list)def total(self):return self.price * self.qtypen = Product("Pen", 20.0, 3)print(pen)print(pen.total(), pen == Product("Pen", 20.0, 3))@dataclass(frozen=True, order=True)class Version:major: intminor: intprint(sorted([Version(2, 1), Version(1, 9), Version(2, 0)]))
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
Product(name='Pen', price=20.0, qty=3, tags=[])
60.0 True
[Version(major=1, minor=9), Version(major=2, minor=0), Version(major=2, minor=1)] ๐ฏ Turn Book into a @dataclass with title: str, author: str and pages: int = 100. print(Book("Gita", "Vyasa")) should show Book(title='Gita', author='Vyasa', pages=100).
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
from dataclasses import dataclass; @dataclass class Book: title: str; author: str; pages: int = 100
- The problemA Product class with name, price and qty needs a 6-line __init__, a __repr__ and an __eq__. A dataclass needs four lines and gets all of it, correct, for free.
- The Python idea
from dataclasses import dataclass, fieldA dataclass is a class mainly for holding data, created with the @dataclass decorator. - In real lifeFastAPI and Pydantic models look just like dataclasses: typed fields that validate incoming JSON automatically.
Start with a question
A Product class with name, price and qty needs a 6-line __init__, a __repr__ and an __eq__. A dataclass needs four lines and gets all of it, correct, for free.
Modern Python uses dataclasses (and their cousins in Pydantic) for config, API models and records everywhere.
Explain it like I'm 10
A dataclass is a ready-made form: you just write the field names, and Python builds the boxes, labels and checks for you.
The technical explanation
@dataclass class Point: x: int; y: int gives you Point(1, 2), a readable repr and == that compares fields.
Defaults work like functions: qty: int = 1. Mutable defaults need field(default_factory=list).
@dataclass(frozen=True) makes objects read-only; order=True adds <, > so they sort by their fields.
Syntax
from dataclasses import dataclass, field
@dataclass
class Name:
a: int
b: str = "x" Real-world scenario
FastAPI and Pydantic models look just like dataclasses: typed fields that validate incoming JSON automatically.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Iterators โQuestions people ask
When should I use a dataclass instead of a normal class?
When the class mainly holds data. You still can add methods. For classes that are mostly behaviour with little data, a normal class is fine.
What is the difference between dataclasses and Pydantic?
Dataclasses (standard library) generate methods but do not validate types at run time. Pydantic models validate and convert data, which suits API input.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner When should I use a dataclass instead of a normal class?
When the class mainly holds data. You still can add methods. For classes that are mostly behaviour with little data, a normal class is fine.
beginner What is the difference between dataclasses and Pydantic?
Dataclasses (standard library) generate methods but do not validate types at run time. Pydantic models validate and convert data, which suits API input.
intermediate Which methods does @dataclass write for you?
__init__, __repr__, __eq__. Those three by default.
intermediate How do you declare fields?
With type-hinted class attributes. name: str, price: floatโฆ
Quick revision
Remember
- Define a @dataclass with typed fields
- Use defaults and field(default_factory=list)
- Use frozen and order
- Never write
items: list = []in a dataclass. Useitems: list = field(default_factory=list)so each object gets its own list.
Syntax
from dataclasses import dataclass, field
@dataclass
class Name:
a: int
b: str = "x" Official documentation
- dataclasses (docs.python.org)