Home β€Ί Curriculum β€Ί Dataclasses
Intermediate Β· Python 3.10+ Β· Free & interactive

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.

16
Runnable programs
8
Lessons
12
Options covered

πŸ“– 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.

πŸ’‘ A dataclass is still a completely normal class. You can add your own methods, properties, class variables, and inheritance. The decorator only adds methods; it does not use a special base class or metaclass.

🎯 What you will learn

  • βœ“What @dataclass generates 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__ and InitVar
  • βœ“How ordering, sorting, and hashing work (and why frozen matters)
  • βœ“How to copy with replace() and convert with asdict() / 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

  1. Read the short explanation at the top of each lesson.
  2. Press Run on the program. Python runs in your browser with Pyodide, so nothing needs installing.
  3. Compare your result with the Expected output box.
  4. Read the line-by-line explanation. The numbered badges match the line numbers in the code (blank lines are not numbered).
  5. 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 addedSwitchWhat it does
__init__init=TrueTakes one parameter per field, assigns them
__repr__repr=TruePoint(x=1, y=2) style text
__eq__eq=TrueCompares all fields as a tuple
__lt__ __le__ __gt__ __ge__order=FalseSorting, only if you ask
__hash__depends on eq, frozenSee the hashing table in Lesson 5
__setattr__ / __delattr__frozen=FalseRaise an error, only when frozen
__match_args__match_args=TrueLets 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_factory for lists, dicts, and sets. Never write = [].
  • 4Validate in __post_init__. Then every object is checked in one place.
  • 5Prefer frozen=True for value-like data. Immutable objects are safer and can be dictionary keys.
πŸ’‘ Annotations are not type checks at runtime. Point("a", "b") runs. Use an editor or a checker such as mypy to catch type mistakes before running.

πŸ†š Dataclass, namedtuple, or plain class?

NeedBest choice
Mutable record with defaults and validation@dataclass
Immutable record, can be a dict key@dataclass(frozen=True)
Tiny immutable tuple that must also unpacknamedtuple / typing.NamedTuple
Rich behavior, little stored dataPlain 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.

OptionDefaultEffectLesson
initTrueGenerate __init__1
reprTrueGenerate __repr__1
eqTrueGenerate __eq__1
orderFalseGenerate comparison methods5
frozenFalseMake instances read-only6
unsafe_hashFalseForce a __hash__ even if mutable5
slotsFalseUse __slots__ (3.10+)7
kw_onlyFalseAll 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.

@dataclassfields__init____repr____eq__

The old way: 14 lines for two fields

Expected output
PointOld(x=1, y=2)
True
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Starts a plain class named PointOld that stores two numbers.
  2. 2
    Defines __init__, the setup method Python calls when you write PointOld(1, 2).
  3. 3
    Saves the first argument on the object as x.
  4. 4
    Saves the second argument as y. Notice we have typed the names x and y three times already (parameter, attribute, and later in __repr__). That repetition is the boilerplate.
  5. 5
    Defines __repr__ so printing the object is readable instead of <PointOld object at 0x...>.
  6. 6
    Builds the text by hand with an f-string. Add a field later and you must remember to edit this line too.
  7. 7
    Defines __eq__ so two points with the same coordinates count as equal (see the Dunder Methods lesson).
  8. 8
    Checks the other object is also a PointOld.
  9. 9
    If it is not, returns NotImplemented, which tells Python to try something else instead of guessing.
  10. 10
    Compares the two points as tuples: (1, 2) == (1, 2) is True.
  11. 11
    Prints the object. It uses our __repr__ and shows PointOld(x=1, y=2).
  12. 12
    Compares two separate but identical points. Prints True thanks to __eq__.

The dataclass way: 5 lines, same behavior

Now the same class with @dataclass. Run both and compare the output.

Expected output
Point(x=1, y=2)
True
3
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the dataclass decorator from the standard-library dataclasses module. Nothing to install.
  2. 2
    The @dataclass decorator inspects the class right after it is built and writes __init__, __repr__, and __eq__ for you.
  3. 3
    A normal class statement. We do not write any methods.
  4. 4
    x: int is a field: a name plus a type annotation. The annotation is what tells @dataclass this name is data. It becomes the first __init__ parameter.
  5. 5
    The second field and the second __init__ parameter. Order matters: fields are used in the order you declare them.
  6. 6
    Creates a point with the generated __init__. Same call as the long version.
  7. 7
    Prints Point(x=1, y=2). The generated __repr__ lists every field by name.
  8. 8
    Compares two points. The generated __eq__ compares all fields as tuples, so this prints True.
  9. 9
    Fields are ordinary attributes, so p.x + p.y is 1 + 2 and prints 3.
πŸ’‘ Type hints are not enforced. 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=...).
defaultfield()default_factory

Defaults and default_factory

Expected output
Student(name='Ana', grade=1, tags=['math'])
Student(name='Ben', grade=3, tags=[])
False
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports dataclass and field. We need field for the list default.
  2. 2
    Turns the class below into a dataclass.
  3. 3
    Starts the Student class.
  4. 4
    A required field. It has no default, so every student must be given a name.
  5. 5
    A field with a simple default. If the caller leaves it out, grade is 1.
  6. 6
    A list field. Mutable defaults such as lists are not allowed directly, so default_factory=list says: “call list() to make a fresh empty list for every new object.”
  7. 7
    Creates Ana using only the required field. She gets grade=1 and her own empty list.
  8. 8
    Creates Ben and overrides the default grade with 3.
  9. 9
    Adds "math" to Ana's list only.
  10. 10
    Prints Ana. Her tags list shows ['math'].
  11. 11
    Prints Ben. His list is still empty because it is a different list.
  12. 12
    Checks whether both students share one list object. Prints False, which is exactly what we want.

Why mutable defaults are blocked

Expected output
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the decorator.
  2. 2
    Starts a try block because we expect the class definition itself to fail.
  3. 3
    Applies @dataclass. The check happens here, when the decorator runs.
  4. 4
    Starts the class Bad.
  5. 5
    Gives the field a plain list [] as its default. If Python allowed this, every object would share the same list.
  6. 6
    Catches the ValueError that @dataclass raises to protect you.
  7. 7
    Prints the error. It says the mutable default is not allowed and tells you to use default_factory.
πŸ’‘ A classic bug in ordinary classes is 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.

field()repr=Falsecompare=Falseinit=False
Expected output
Account(owner='Lea', balance=50.0, id=0)
True
['opened'] []
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports dataclass and field.
  2. 2
    Makes the class a dataclass.
  3. 3
    Starts the Account class.
  4. 4
    A plain required field.
  5. 5
    A plain field with the default 0.0.
  6. 6
    repr=False hides the password from the printed text, so it never leaks into logs. It is still stored and still a normal parameter.
  7. 7
    A list field that is hidden from repr and also ignored by == (compare=False), because a history log should not decide whether two accounts are equal.
  8. 8
    init=False removes id from __init__, so callers cannot pass it. It starts at its default 0 and can be set later by your own code.
  9. 9
    Creates an account, passing owner, balance, and password by position.
  10. 10
    Records an event in the account's log.
  11. 11
    Prints the account. Only owner, balance, and id appear. The password and log are hidden.
  12. 12
    Builds a second account with the same values but an empty log.
  13. 13
    Prints True. The logs differ, but compare=False excluded them from equality.
  14. 14
    Shows the two logs: ['opened'] []. They are separate lists.
πŸ’‘ Other 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.

__post_init__InitVarvalidation

Validation and derived values with __post_init__

Expected output
Rectangle(width=3, height=4, area=12)
Error: sides must be positive
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the tools we need.
  2. 2
    Makes the class a dataclass.
  3. 3
    Starts Rectangle.
  4. 4
    Required field for the width.
  5. 5
    Required field for the height.
  6. 6
    A derived field. init=False means the caller does not supply it; we calculate it ourselves below.
  7. 7
    __post_init__ is a hook. The generated __init__ assigns all fields first and then calls this method automatically.
  8. 8
    Validation: rejects zero or negative sides.
  9. 9
    Raises ValueError with a clear message. The object is never handed back to the caller.
  10. 10
    Computes the area from the two fields and stores it.
  11. 11
    Creates a valid rectangle. __post_init__ runs silently and fills in area.
  12. 12
    Prints Rectangle(width=3, height=4, area=12).
  13. 13
    Starts a try block to test bad input.
  14. 14
    Tries a rectangle with width -1. __post_init__ raises before the object exists.
  15. 15
    Catches the ValueError.
  16. 16
    Prints Error: sides must be positive.

Init-only values with InitVar

Expected output
User(name='kai', length=5)
False
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports InitVar as well.
  2. 2
    Makes the class a dataclass.
  3. 3
    Starts User.
  4. 4
    A normal field.
  5. 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__.
  6. 6
    A derived field that is not part of __init__.
  7. 7
    __post_init__ receives the InitVar as an extra argument.
  8. 8
    Uses the password to compute length. The password itself is never saved on the object.
  9. 9
    Creates a user. The second argument is the init-only password.
  10. 10
    Prints User(name='kai', length=5). No password anywhere.
  11. 11
    Prints False, confirming the password was not stored.
πŸ’‘ Validation belongs in __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:

eqfrozenResult for __hash__
True (default)False (default)Set to None: unhashable
TrueTrueGenerated from the fields: hashable
FalseanyInherited 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.

order=Truesorted()frozen__hash__

Ordering and sorting

Expected output
[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'
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the decorator.
  2. 2
    order=True also generates __lt__, __le__, __gt__, and __ge__.
  3. 3
    Starts Version.
  4. 4
    The first field is compared first.
  5. 5
    The second field breaks ties. Comparison works like comparing tuples: (major, minor).
  6. 6
    Makes a list of three versions in jumbled order.
  7. 7
    sorted() uses the generated <. Prints the versions from 0.9 to 1.5.
  8. 8
    Compares (1, 2) with (1, 5). Prints True.
  9. 9
    max() also uses ordering and prints Version(major=1, minor=5).
  10. 10
    Starts a try block to test putting a version in a set.
  11. 11
    A set literal needs to hash its items. A normal dataclass has eq=True and is mutable, so Python sets __hash__ to None.
  12. 12
    Catches the TypeError.
  13. 13
    Prints TypeError: unhashable type: 'Version'.
πŸ’‘ Ordering compares fields in the order you declared them. Put the most important field first.

Hashing: sets and dictionary keys

Expected output
2
Cebu
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the decorator.
  2. 2
    frozen=True makes instances read-only. With eq=True (the default), Python then generates a matching __hash__.
  3. 3
    Starts Coord.
  4. 4
    Latitude field.
  5. 5
    Longitude field.
  6. 6
    Builds a set with three coordinates, two of them equal. Equal objects have equal hashes, so duplicates collapse.
  7. 7
    Prints 2, not 3.
  8. 8
    Uses a coordinate as a dictionary key, which requires hashing.
  9. 9
    Looks 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.

frozenreplace()asdict()astuple()

Frozen objects, replace(), asdict() and astuple()

Expected output
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)
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the dataclass tools: replace (copy with changes), asdict, astuple, and the error class for frozen objects.
  2. 2
    frozen=True makes every instance immutable.
  3. 3
    Starts Settings.
  4. 4
    A field with a default.
  5. 5
    Another field with a default.
  6. 6
    Creates settings using both defaults.
  7. 7
    Starts a try block to test changing a field.
  8. 8
    Tries to assign to a field of a frozen object.
  9. 9
    Catches FrozenInstanceError, which is a kind of AttributeError.
  10. 10
    Prints Blocked: cannot assign to field 'theme'.
  11. 11
    replace() builds a new object with the same values except theme. The original is untouched.
  12. 12
    Prints the original: still dark.
  13. 13
    Prints the copy: now light.
  14. 14
    asdict() converts the object to a plain dictionary.
  15. 15
    astuple() converts it to a tuple of field values.

Nested dataclasses to JSON

Expected output
{'name': 'Mia', 'address': {'city': 'Dipolog', 'country': 'Philippines'}}
{"name": "Mia", "address": {"city": "Dipolog", "country": "Philippines"}}
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports dataclass and asdict.
  2. 2
    Imports the json module from the standard library.
  3. 3
    Makes Address a dataclass.
  4. 4
    Starts the class.
  5. 5
    City field.
  6. 6
    Country field.
  7. 7
    Makes Person a dataclass.
  8. 8
    Starts the class.
  9. 9
    Name field.
  10. 10
    A field whose value is itself a dataclass.
  11. 11
    Builds a person containing a nested address.
  12. 12
    asdict() works recursively: the nested address becomes a nested dictionary too.
  13. 13
    Prints the dictionary.
  14. 14
    Converts 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=Truekw_only=Trueinheritance

slots=True: smaller and stricter objects

Expected output
False
No new attributes allowed
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the decorator.
  2. 2
    slots=True (Python 3.10+) stores fields in fixed slots instead of a per-object dictionary.
  3. 3
    Starts Light.
  4. 4
    First field.
  5. 5
    Second field.
  6. 6
    Creates an instance.
  7. 7
    Checks for a __dict__. Prints False: there is no dictionary, which saves memory.
  8. 8
    Starts a try block.
  9. 9
    Tries to add an attribute that is not a declared field.
  10. 10
    Slotted objects reject unknown attributes with AttributeError.
  11. 11
    Prints No new attributes allowed. This also catches typos like pt.xx = 5.

Inheritance and keyword-only fields

Expected output
Dog(name='Rex', age=3, breed='Aspin')
Order(item='Book', qty=1, express=True)
TypeError: use keyword arguments
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the decorator.
  2. 2
    Makes Animal a dataclass.
  3. 3
    Starts the parent class.
  4. 4
    Required field.
  5. 5
    Field with a default.
  6. 6
    Makes Dog a dataclass too. Every class in the chain needs its own decorator.
  7. 7
    Dog inherits from Animal.
  8. 8
    Adds one more field. Parent fields come first, so the order is name, age, breed.
  9. 9
    kw_only=True (Python 3.10+) makes every field of Order keyword-only.
  10. 10
    Starts Order.
  11. 11
    Required field.
  12. 12
    Default quantity.
  13. 13
    Default shipping flag.
  14. 14
    Creates a dog, passing all three values by position.
  15. 15
    Prints Dog(name='Rex', age=3, breed='Aspin').
  16. 16
    Creates an order with keyword arguments only. It is clear what True means.
  17. 17
    Prints the order.
  18. 18
    Starts a try block.
  19. 19
    Passing "Book" by position is not allowed.
  20. 20
    Catches the TypeError.
  21. 21
    Prints our message.
πŸ’‘ With inheritance, a parent field with a default followed by a child field without a default raises 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.

frozenorder=Truedefault_factory__post_init__
Expected output
Ana 130.0
OrderLine(product=Product(sku='P-01', name='Pen', price=12.5), qty=4)
Notebook
1
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports dataclass and field.
  2. 2
    Product is frozen (safe to share and hash) and ordered (sortable).
  3. 3
    Starts Product.
  4. 4
    The SKU is the identity. It is the only field used for comparing, sorting, and hashing.
  5. 5
    The name is descriptive data, so compare=False keeps it out of equality and ordering.
  6. 6
    The price can change between catalog versions without making it a different product, so it is also excluded.
  7. 7
    OrderLine is a regular mutable dataclass.
  8. 8
    Starts OrderLine.
  9. 9
    The product being bought, itself a dataclass.
  10. 10
    Quantity, defaulting to one.
  11. 11
    __post_init__ runs after the generated __init__.
  12. 12
    Checks the quantity.
  13. 13
    Rejects quantities below one, so invalid lines can never exist.
  14. 14
    @property lets you write line.total without parentheses. Properties are not fields.
  15. 15
    Defines the computed total.
  16. 16
    Multiplies price by quantity.
  17. 17
    Order groups many lines for one customer.
  18. 18
    Starts Order.
  19. 19
    Customer name.
  20. 20
    A list of lines. default_factory=list gives each order its own list.
  21. 21
    A normal method on a dataclass. Dataclasses can have any methods you like.
  22. 22
    Creates an OrderLine and appends it.
  23. 23
    Another computed property, this time for the whole order.
  24. 24
    Defines total for the order.
  25. 25
    Sums every line's total with a generator expression.
  26. 26
    Creates a pen product.
  27. 27
    Creates a notebook product.
  28. 28
    Starts an order for Ana.
  29. 29
    Adds four pens: 4 × 12.5 = 50.0.
  30. 30
    Adds one notebook with the default quantity: 80.0.
  31. 31
    Prints Ana 130.0.
  32. 32
    Prints the first line. Nested dataclass repr output shows everything.
  33. 33
    Sorts products by SKU (B-07 comes before P-01) and prints the first name: Notebook.
  34. 34
    Builds a set with the pen and a pen with different name and price but the same SKU. They are equal, so the set has 1 item.
πŸ’‘ Design tip: decide what makes two objects “the same thing” (here, the SKU) and put only those fields in 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

Expected output
TypeError raised
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports the decorator.
  2. 2
    A try block, since defining the class will fail.
  3. 3
    Applies @dataclass.
  4. 4
    Starts Item.
  5. 5
    A field with a default.
  6. 6
    A field without a default placed after one that has a default. The generated __init__ would be (name="x", price), which is not valid Python.
  7. 7
    Catches the resulting TypeError.
  8. 8
    Prints TypeError raised.

Mistake 2: setting a derived field on a frozen class

Expected output
Circle(radius=2, area=12.56636)
πŸ“– Line-by-line explanation
Numbers match the code above. Blank lines are not numbered.
  1. 1
    Imports what we need.
  2. 2
    A frozen dataclass.
  3. 3
    Starts Circle.
  4. 4
    The radius field.
  5. 5
    A derived field that is not in __init__.
  6. 6
    __post_init__ must fill area.
  7. 7
    Writing self.area = ... would raise FrozenInstanceError. The standard workaround is object.__setattr__, which bypasses the frozen check. Use it only inside __post_init__.
  8. 8
    Creates a circle with radius 2.
  9. 9
    Prints Circle(radius=2, area=12.56636).
πŸ’‘ Fix for mistake 1: give 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 writeMeaning
@dataclassGenerate __init__, __repr__, __eq__
x: intRequired field
x: int = 0Optional 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] = 5Class-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
πŸ’‘ Tip: run 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.

  1. Contact card. Create a Contact dataclass with name, phone, and a list of emails (use default_factory). Print two contacts and compare them with ==.
  2. Validated temperature. Write Temperature(celsius) with a __post_init__ that rejects values below -273.15 and a derived fahrenheit field.
  3. Sortable students. Build a Student(grade, name) with order=True. Sort a list from highest to lowest grade using reverse=True.
  4. Frozen config. Make a frozen Config with three fields. Use replace() to create a modified copy and show the original is unchanged.
  5. Shopping cart. Write Item and Cart dataclasses. Cart keeps a list of items and has a total property.
  6. 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.