Python Dataclasses
Skip the boilerplate, keep the power
A dataclass is a normal class where Python writes the repetitive methods for you. Declare the fields, add @dataclass, and you get __init__, __repr__, and __eq__ for free, plus optional ordering, hashing, immutability, and memory savings. This lesson explains the idea from scratch and walks through 16 runnable programs, each one explained line by line.
π Welcome: Why Dataclasses Matter
π€ The big idea
Think about the classes you have written that mostly store values: a Student with a name and grade, an Order with items, a Point with two coordinates. Each one needs an __init__ that copies arguments into attributes, a __repr__ so printing is readable, and an __eq__ so two equal objects compare equal. That is the same code over and over, and every time you add a field you must update three methods.
A dataclass removes that work. You list the fields with type annotations, and the @dataclass decorator (in the standard-library dataclasses module since Python 3.7) generates the methods from that list. Add a field in one place and everything stays in sync.
π― What you will learn
- βWhat
@dataclassgenerates and when to use it - βHow to declare fields, set defaults, and avoid the mutable-default trap
- βHow to fine-tune each field with
field():default_factory,repr,compare,init - βHow to validate and compute values with
__post_init__andInitVar - βHow ordering, sorting, and hashing work (and why frozen matters)
- βHow to copy with
replace()and convert withasdict()/astuple() - βHow to use
slots=True,kw_only=True, and inheritance - βHow to avoid the most common mistakes
π Before you start
You should be comfortable with classes (__init__, self, attributes) and functions with default arguments. The Dunder Methods lesson is a great companion: it shows the methods that dataclasses write for you. Knowing lists and dictionaries helps too.
How to use this page
- Read the short explanation at the top of each lesson.
- Press Run on the program. Python runs in your browser with Pyodide, so nothing needs installing.
- Compare your result with the Expected output box.
- Read the line-by-line explanation. The numbered badges match the line numbers in the code (blank lines are not numbered).
- Copy the code, change it, and break it on purpose. That is the fastest way to learn.
Estimated time: 2 to 3 hours if you run and modify every example.
βοΈ How Dataclasses Actually Work
π What @dataclass generates
When Python finishes building your class, the decorator reads the annotated names in order, treats them as fields, and adds methods to the class. By default you get:
| Method added | Switch | What it does |
|---|---|---|
__init__ | init=True | Takes one parameter per field, assigns them |
__repr__ | repr=True | Point(x=1, y=2) style text |
__eq__ | eq=True | Compares all fields as a tuple |
__lt__ __le__ __gt__ __ge__ | order=False | Sorting, only if you ask |
__hash__ | depends on eq, frozen | See the hashing table in Lesson 5 |
__setattr__ / __delattr__ | frozen=False | Raise an error, only when frozen |
__match_args__ | match_args=True | Lets dataclasses work in match statements |
π Five golden rules
- 1Annotate every field. A name without an annotation is a plain class attribute, not a field.
- 2Required fields first. Fields with defaults must come after fields without.
- 3Use
default_factoryfor lists, dicts, and sets. Never write= []. - 4Validate in
__post_init__. Then every object is checked in one place. - 5Prefer
frozen=Truefor value-like data. Immutable objects are safer and can be dictionary keys.
Point("a", "b") runs. Use an editor or a checker such as mypy to catch type mistakes before running.π Dataclass, namedtuple, or plain class?
| Need | Best choice |
|---|---|
| Mutable record with defaults and validation | @dataclass |
| Immutable record, can be a dict key | @dataclass(frozen=True) |
| Tiny immutable tuple that must also unpack | namedtuple / typing.NamedTuple |
| Rich behavior, little stored data | Plain class |
| Parse and validate untrusted input (JSON from the web) | A validation library such as Pydantic |
ποΈ The Options Map
These are the switches on @dataclass(...). Each lesson below shows the important ones in action.
| Option | Default | Effect | Lesson |
|---|---|---|---|
init | True | Generate __init__ | 1 |
repr | True | Generate __repr__ | 1 |
eq | True | Generate __eq__ | 1 |
order | False | Generate comparison methods | 5 |
frozen | False | Make instances read-only | 6 |
unsafe_hash | False | Force a __hash__ even if mutable | 5 |
slots | False | Use __slots__ (3.10+) | 7 |
kw_only | False | All fields keyword-only (3.10+) | 7 |
π§± Your First Dataclass Beginner
Many classes exist only to hold data: a point, a student, an order line, a settings object. Writing __init__, __repr__, and __eq__ for each one is repetitive and easy to get wrong. The @dataclass decorator (Python 3.7+) generates them from a list of annotated fields.
The old way: 14 lines for two fields
PointOld(x=1, y=2) True
- 1Starts a plain class named
PointOldthat stores two numbers. - 2Defines
__init__, the setup method Python calls when you writePointOld(1, 2). - 3Saves the first argument on the object as
x. - 4Saves the second argument as
y. Notice we have typed the namesxandythree times already (parameter, attribute, and later in__repr__). That repetition is the boilerplate. - 5Defines
__repr__so printing the object is readable instead of<PointOld object at 0x...>. - 6Builds the text by hand with an f-string. Add a field later and you must remember to edit this line too.
- 7Defines
__eq__so two points with the same coordinates count as equal (see the Dunder Methods lesson). - 8Checks the other object is also a
PointOld. - 9If it is not, returns
NotImplemented, which tells Python to try something else instead of guessing. - 10Compares the two points as tuples:
(1, 2) == (1, 2)isTrue. - 11Prints the object. It uses our
__repr__and showsPointOld(x=1, y=2). - 12Compares two separate but identical points. Prints
Truethanks to__eq__.
The dataclass way: 5 lines, same behavior
Now the same class with @dataclass. Run both and compare the output.
Point(x=1, y=2) True 3
- 1Imports the
dataclassdecorator from the standard-librarydataclassesmodule. Nothing to install. - 2The
@dataclassdecorator inspects the class right after it is built and writes__init__,__repr__, and__eq__for you. - 3A normal class statement. We do not write any methods.
- 4
x: intis a field: a name plus a type annotation. The annotation is what tells@dataclassthis name is data. It becomes the first__init__parameter. - 5The second field and the second
__init__parameter. Order matters: fields are used in the order you declare them. - 6Creates a point with the generated
__init__. Same call as the long version. - 7Prints
Point(x=1, y=2). The generated__repr__lists every field by name. - 8Compares two points. The generated
__eq__compares all fields as tuples, so this printsTrue. - 9Fields are ordinary attributes, so
p.x + p.yis1 + 2and prints3.
Point("a", "b") works fine. The annotation tells @dataclass which names are fields; tools like editors and mypy use the types to catch mistakes.ποΈ Fields, Defaults and default_factory Beginner
Fields work like function parameters. A field without a default is required; a field with = value is optional. Two rules to remember:
- Fields without defaults must come before fields with defaults (same rule as function parameters).
- Lists, dicts, and sets cannot be written directly as defaults. Use
field(default_factory=...).
Defaults and default_factory
Student(name='Ana', grade=1, tags=['math']) Student(name='Ben', grade=3, tags=[]) False
- 1Imports
dataclassandfield. We needfieldfor the list default. - 2Turns the class below into a dataclass.
- 3Starts the
Studentclass. - 4A required field. It has no default, so every student must be given a name.
- 5A field with a simple default. If the caller leaves it out,
gradeis1. - 6A list field. Mutable defaults such as lists are not allowed directly, so
default_factory=listsays: “calllist()to make a fresh empty list for every new object.” - 7Creates Ana using only the required field. She gets
grade=1and her own empty list. - 8Creates Ben and overrides the default grade with
3. - 9Adds
"math"to Ana's list only. - 10Prints Ana. Her tags list shows
['math']. - 11Prints Ben. His list is still empty because it is a different list.
- 12Checks whether both students share one list object. Prints
False, which is exactly what we want.
Why mutable defaults are blocked
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory
- 1Imports the decorator.
- 2Starts a
tryblock because we expect the class definition itself to fail. - 3Applies
@dataclass. The check happens here, when the decorator runs. - 4Starts the class
Bad. - 5Gives the field a plain list
[]as its default. If Python allowed this, every object would share the same list. - 6Catches the
ValueErrorthat@dataclassraises to protect you. - 7Prints the error. It says the mutable default is not allowed and tells you to use
default_factory.
def __init__(self, items=[]), where every object shares one list. Dataclasses refuse to let you make that mistake.π§ Controlling Fields with field() Intermediate
The field() function lets you tune each field individually: hide it from repr, leave it out of comparisons, or exclude it from __init__. Each switch is a keyword argument that defaults to True.
Account(owner='Lea', balance=50.0, id=0) True ['opened'] []
- 1Imports
dataclassandfield. - 2Makes the class a dataclass.
- 3Starts the
Accountclass. - 4A plain required field.
- 5A plain field with the default
0.0. - 6
repr=Falsehides the password from the printed text, so it never leaks into logs. It is still stored and still a normal parameter. - 7A list field that is hidden from
reprand also ignored by==(compare=False), because a history log should not decide whether two accounts are equal. - 8
init=Falseremovesidfrom__init__, so callers cannot pass it. It starts at its default0and can be set later by your own code. - 9Creates an account, passing owner, balance, and password by position.
- 10Records an event in the account's log.
- 11Prints the account. Only
owner,balance, andidappear. The password and log are hidden. - 12Builds a second account with the same values but an empty log.
- 13Prints
True. The logs differ, butcompare=Falseexcluded them from equality. - 14Shows the two logs:
['opened'] []. They are separate lists.
field() options: hash= (include in hash), kw_only=True (keyword-only), and metadata={...} (free-form notes for other tools). Annotate with typing.ClassVar to mark a class-wide value that is not a field.πͺ __post_init__ and InitVar Intermediate
The generated __init__ only copies arguments into fields. When you need to validate input, compute a value, or normalize data, define __post_init__(self). Python calls it right after __init__ finishes.
Validation and derived values with __post_init__
Rectangle(width=3, height=4, area=12) Error: sides must be positive
- 1Imports the tools we need.
- 2Makes the class a dataclass.
- 3Starts
Rectangle. - 4Required field for the width.
- 5Required field for the height.
- 6A derived field.
init=Falsemeans the caller does not supply it; we calculate it ourselves below. - 7
__post_init__is a hook. The generated__init__assigns all fields first and then calls this method automatically. - 8Validation: rejects zero or negative sides.
- 9Raises
ValueErrorwith a clear message. The object is never handed back to the caller. - 10Computes the area from the two fields and stores it.
- 11Creates a valid rectangle.
__post_init__runs silently and fills inarea. - 12Prints
Rectangle(width=3, height=4, area=12). - 13Starts a
tryblock to test bad input. - 14Tries a rectangle with width
-1.__post_init__raises before the object exists. - 15Catches the
ValueError. - 16Prints
Error: sides must be positive.
Init-only values with InitVar
User(name='kai', length=5) False
- 1Imports
InitVaras well. - 2Makes the class a dataclass.
- 3Starts
User. - 4A normal field.
- 5
InitVar[str]marks a parameter that goes into__init__but is not stored as a field. It is only passed along to__post_init__. - 6A derived field that is not part of
__init__. - 7
__post_init__receives theInitVaras an extra argument. - 8Uses the password to compute
length. The password itself is never saved on the object. - 9Creates a user. The second argument is the init-only password.
- 10Prints
User(name='kai', length=5). No password anywhere. - 11Prints
False, confirming the password was not stored.
__post_init__, not in the callers. Then every way of creating the object is checked in one place.βοΈ Ordering, Sorting and Hashing Intermediate
By default a dataclass compares with == but not with <. Switch on order=True to sort. Hashing follows a rule you should memorize:
eq | frozen | Result for __hash__ |
|---|---|---|
True (default) | False (default) | Set to None: unhashable |
True | True | Generated from the fields: hashable |
False | any | Inherited from object (identity) |
The reason: a mutable object whose hash can change would get lost inside a set. This is the same lesson as __eq__ and __hash__ in the Dunder Methods page.
Ordering and sorting
[Version(major=0, minor=9), Version(major=1, minor=2), Version(major=1, minor=5)] True Version(major=1, minor=5) TypeError: unhashable type: 'Version'
- 1Imports the decorator.
- 2
order=Truealso generates__lt__,__le__,__gt__, and__ge__. - 3Starts
Version. - 4The first field is compared first.
- 5The second field breaks ties. Comparison works like comparing tuples:
(major, minor). - 6Makes a list of three versions in jumbled order.
- 7
sorted()uses the generated<. Prints the versions from0.9to1.5. - 8Compares
(1, 2)with(1, 5). PrintsTrue. - 9
max()also uses ordering and printsVersion(major=1, minor=5). - 10Starts a
tryblock to test putting a version in a set. - 11A set literal needs to hash its items. A normal dataclass has
eq=Trueand is mutable, so Python sets__hash__toNone. - 12Catches the
TypeError. - 13Prints
TypeError: unhashable type: 'Version'.
Hashing: sets and dictionary keys
2 Cebu
- 1Imports the decorator.
- 2
frozen=Truemakes instances read-only. Witheq=True(the default), Python then generates a matching__hash__. - 3Starts
Coord. - 4Latitude field.
- 5Longitude field.
- 6Builds a set with three coordinates, two of them equal. Equal objects have equal hashes, so duplicates collapse.
- 7Prints
2, not3. - 8Uses a coordinate as a dictionary key, which requires hashing.
- 9Looks it up with a new but equal coordinate. Prints
Cebu.
π§ Frozen Objects and Converting Data Intermediate
Immutable objects are easier to reason about: they cannot change behind your back, and they are safe as dictionary keys. frozen=True blocks assignment. To “change” a frozen object you create a modified copy with replace(). The helper functions asdict() and astuple() convert objects to plain data.
Frozen objects, replace(), asdict() and astuple()
Blocked: cannot assign to field 'theme'
Settings(theme='dark', font_size=14)
Settings(theme='light', font_size=14)
{'theme': 'light', 'font_size': 14}
('light', 14)- 1Imports the dataclass tools:
replace(copy with changes),asdict,astuple, and the error class for frozen objects. - 2
frozen=Truemakes every instance immutable. - 3Starts
Settings. - 4A field with a default.
- 5Another field with a default.
- 6Creates settings using both defaults.
- 7Starts a
tryblock to test changing a field. - 8Tries to assign to a field of a frozen object.
- 9Catches
FrozenInstanceError, which is a kind ofAttributeError. - 10Prints
Blocked: cannot assign to field 'theme'. - 11
replace()builds a new object with the same values excepttheme. The original is untouched. - 12Prints the original: still
dark. - 13Prints the copy: now
light. - 14
asdict()converts the object to a plain dictionary. - 15
astuple()converts it to a tuple of field values.
Nested dataclasses to JSON
{'name': 'Mia', 'address': {'city': 'Dipolog', 'country': 'Philippines'}}
{"name": "Mia", "address": {"city": "Dipolog", "country": "Philippines"}}- 1Imports
dataclassandasdict. - 2Imports the
jsonmodule from the standard library. - 3Makes
Addressa dataclass. - 4Starts the class.
- 5City field.
- 6Country field.
- 7Makes
Persona dataclass. - 8Starts the class.
- 9Name field.
- 10A field whose value is itself a dataclass.
- 11Builds a person containing a nested address.
- 12
asdict()works recursively: the nested address becomes a nested dictionary too. - 13Prints the dictionary.
- 14Converts it to a JSON string. This is the easiest way to save or send dataclasses.
π slots, kw_only and Inheritance Advanced
Three options polish a dataclass for real projects. slots=True reduces memory and blocks stray attributes. kw_only=True forces callers to name every argument, which is ideal for classes with many fields. Inheritance works as you would expect: child classes add fields after the parent's.
slots=True: smaller and stricter objects
False No new attributes allowed
- 1Imports the decorator.
- 2
slots=True(Python 3.10+) stores fields in fixed slots instead of a per-object dictionary. - 3Starts
Light. - 4First field.
- 5Second field.
- 6Creates an instance.
- 7Checks for a
__dict__. PrintsFalse: there is no dictionary, which saves memory. - 8Starts a
tryblock. - 9Tries to add an attribute that is not a declared field.
- 10Slotted objects reject unknown attributes with
AttributeError. - 11Prints
No new attributes allowed. This also catches typos likept.xx = 5.
Inheritance and keyword-only fields
Dog(name='Rex', age=3, breed='Aspin') Order(item='Book', qty=1, express=True) TypeError: use keyword arguments
- 1Imports the decorator.
- 2Makes
Animala dataclass. - 3Starts the parent class.
- 4Required field.
- 5Field with a default.
- 6Makes
Doga dataclass too. Every class in the chain needs its own decorator. - 7
Doginherits fromAnimal. - 8Adds one more field. Parent fields come first, so the order is
name,age,breed. - 9
kw_only=True(Python 3.10+) makes every field ofOrderkeyword-only. - 10Starts
Order. - 11Required field.
- 12Default quantity.
- 13Default shipping flag.
- 14Creates a dog, passing all three values by position.
- 15Prints
Dog(name='Rex', age=3, breed='Aspin'). - 16Creates an order with keyword arguments only. It is clear what
Truemeans. - 17Prints the order.
- 18Starts a
tryblock. - 19Passing
"Book"by position is not allowed. - 20Catches the
TypeError. - 21Prints our message.
TypeError. Using kw_only=True on the child avoids the ordering problem.π Putting It Together: an Order System Advanced
This capstone uses almost everything from the lesson: frozen and ordered dataclasses, field(compare=False), default_factory, __post_init__ validation, nested dataclasses, and computed properties. Read it top to bottom, then run it.
Ana 130.0 OrderLine(product=Product(sku='P-01', name='Pen', price=12.5), qty=4) Notebook 1
- 1Imports
dataclassandfield. - 2
Productis frozen (safe to share and hash) and ordered (sortable). - 3Starts
Product. - 4The SKU is the identity. It is the only field used for comparing, sorting, and hashing.
- 5The name is descriptive data, so
compare=Falsekeeps it out of equality and ordering. - 6The price can change between catalog versions without making it a different product, so it is also excluded.
- 7
OrderLineis a regular mutable dataclass. - 8Starts
OrderLine. - 9The product being bought, itself a dataclass.
- 10Quantity, defaulting to one.
- 11
__post_init__runs after the generated__init__. - 12Checks the quantity.
- 13Rejects quantities below one, so invalid lines can never exist.
- 14
@propertylets you writeline.totalwithout parentheses. Properties are not fields. - 15Defines the computed total.
- 16Multiplies price by quantity.
- 17
Ordergroups many lines for one customer. - 18Starts
Order. - 19Customer name.
- 20A list of lines.
default_factory=listgives each order its own list. - 21A normal method on a dataclass. Dataclasses can have any methods you like.
- 22Creates an
OrderLineand appends it. - 23Another computed property, this time for the whole order.
- 24Defines
totalfor the order. - 25Sums every line's total with a generator expression.
- 26Creates a pen product.
- 27Creates a notebook product.
- 28Starts an order for Ana.
- 29Adds four pens:
4 × 12.5 = 50.0. - 30Adds one notebook with the default quantity:
80.0. - 31Prints
Ana 130.0. - 32Prints the first line. Nested dataclass
reproutput shows everything. - 33Sorts products by SKU (
B-07comes beforeP-01) and prints the first name:Notebook. - 34Builds a set with the pen and a pen with different name and price but the same SKU. They are equal, so the set has
1item.
eq, ordering, and hashing. Everything else is compare=False.β οΈ Common Mistakes (and How to Avoid Them)
Two errors almost every beginner meets. A third one, the mutable default, was shown in Lesson 2.
Mistake 1: a required field after a default field
TypeError raised
- 1Imports the decorator.
- 2A
tryblock, since defining the class will fail. - 3Applies
@dataclass. - 4Starts
Item. - 5A field with a default.
- 6A field without a default placed after one that has a default. The generated
__init__would be(name="x", price), which is not valid Python. - 7Catches the resulting
TypeError. - 8Prints
TypeError raised.
Mistake 2: setting a derived field on a frozen class
Circle(radius=2, area=12.56636)
- 1Imports what we need.
- 2A frozen dataclass.
- 3Starts
Circle. - 4The radius field.
- 5A derived field that is not in
__init__. - 6
__post_init__must fillarea. - 7Writing
self.area = ...would raiseFrozenInstanceError. The standard workaround isobject.__setattr__, which bypasses the frozen check. Use it only inside__post_init__. - 8Creates a circle with radius 2.
- 9Prints
Circle(radius=2, area=12.56636).
price a default, move it above name, or use kw_only=True.π Dataclasses Cheat Sheet
Bookmark this page. These are the pieces you will use most.
| You write | Meaning |
|---|---|
@dataclass | Generate __init__, __repr__, __eq__ |
x: int | Required field |
x: int = 0 | Optional field with default |
x: list = field(default_factory=list) | Fresh mutable default per object |
field(repr=False) | Hide from repr |
field(compare=False) | Ignore in ==, ordering, and hash |
field(init=False) | Not an __init__ parameter |
field(kw_only=True) | This field must be passed by keyword |
x: InitVar[int] | Init-only parameter, passed to __post_init__ |
x: ClassVar[int] = 5 | Class-wide value, not a field |
def __post_init__(self) | Runs after __init__: validate or compute |
@dataclass(order=True) | Enable < <= > >= and sorting |
@dataclass(frozen=True) | Immutable and hashable |
@dataclass(slots=True) | Smaller objects, no stray attributes |
@dataclass(kw_only=True) | All fields keyword-only |
replace(obj, x=1) | Copy with changes |
asdict(obj) / astuple(obj) | Convert to dict / tuple (recursive) |
fields(obj) | Inspect the list of fields |
is_dataclass(x) | Check whether something is a dataclass |
help(dataclasses) or read dataclasses.fields(obj) to see exactly which fields Python registered for your class.ποΈ Practice Challenges
Reading is not enough. Try these on your own, then compare with the lesson code.
- Contact card. Create a
Contactdataclass withname,phone, and a list ofemails(usedefault_factory). Print two contacts and compare them with==. - Validated temperature. Write
Temperature(celsius)with a__post_init__that rejects values below-273.15and a derivedfahrenheitfield. - Sortable students. Build a
Student(grade, name)withorder=True. Sort a list from highest to lowest grade usingreverse=True. - Frozen config. Make a frozen
Configwith three fields. Usereplace()to create a modified copy and show the original is unchanged. - Shopping cart. Write
ItemandCartdataclasses.Cartkeeps a list of items and has atotalproperty. - JSON round trip. Convert a nested dataclass to JSON with
asdict(), then rebuild the objects from the dictionary by hand.
β Frequently Asked Questions
No. Annotations are documentation for you, your editor, and type checkers like mypy. At runtime Python does not enforce them. If you need real checks, add them in __post_init__ or use a validation library.
All instances would share the same list, so changing one object's list would change every object's. Dataclasses raise ValueError to stop this. Use field(default_factory=list).
With eq=True and not frozen, Python sets __hash__ to None, because mutable objects should not be hashed. Make it frozen=True if the data is a value.
Yes. Add methods, properties, class methods, and static methods exactly as in any class. If you define __repr__ or __eq__ yourself, the decorator keeps yours.
Use a dataclass when you want defaults, validation, methods, or mutability. Use a named tuple when you need a tiny immutable record that also behaves like a tuple (indexing and unpacking).
When you create many instances (thousands or more) and want lower memory use, or when you want typos like obj.nmae = 1 to fail loudly. It needs Python 3.10 or newer.
π Where to go next
Revisit Dunder Methods to see by hand what @dataclass writes for you, review Python Classes, or continue with the next lesson in the curriculum.