A data class, created with the @dataclass decorator from the dataclasses module, is a class built mainly to hold data, with common boilerplate — a constructor, a readable __str__, and equality comparison — generated automatically instead of hand-written. It's the modern, concise way to write a simple class whose main job is bundling a few related values together.
#how it works
1
Import dataclass
From the dataclasses module, part of the standard library.
2
Decorate a class with @dataclass
Then list its fields as simple type-annotated class attributes.
3
__init__() is generated automatically
No manual constructor is needed for the listed fields.
4
A readable __str__ is generated too
Showing every field’s value, instead of a default memory address.
5
__eq__ is generated as well
Comparing instances field by field, rather than the default identity-only comparison.
#example
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p1 = Point(3, 4)
p2 = Point(3, 4)
print(p1)
print(p1 == p2)
Output
Point(x=3, y=4)
True
1@dataclass on Point automatically generates __init__(self, x, y), so Point(3, 4) just works, without writing a constructor by hand.
2Printing p1 shows a clear, labeled representation, Point(x=3, y=4), generated automatically rather than a default, unhelpful memory address.
3p1 == p2 compares field by field (x and y), returning True since both hold identical values — a plain class without @dataclass would compare by identity instead, returning False here.
#use cases
Writing simple data-holding classes without repeating the same __init__/__str__/__eq__ boilerplate every time
Representing structured records, like configuration settings or API request/response shapes
Getting free, correct equality comparison for classes that are really just a bundle of related values
A modern alternative to namedtuple when the fields need to be mutable, or when default values and methods are also needed
Practice Python interview questions
Every Python lesson maps to the matching interview topic, with answers written for current Python versions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free →Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →