Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 149 ยท Object-Oriented Programming

Data Classes

Learn Python data classes - let @dataclass write __init__, __repr__ and __eq__, set defaults safely with field(), and make frozen, ordered and slotted classes.

Many classes exist mainly to hold data: a point with x and y, a product with a name and a price, a settings object with a dozen options. Writing them by hand means typing every field three times: as an __init__ parameter, as self.field = field, and again in __repr__ and __eq__. That's tedious and easy to get wrong.

The dataclasses module fixes this. Decorate a class with @dataclass, list its fields with type hints, and Python generates __init__, __repr__ and __eq__ for you. You can still add your own methods and properties like in any other class.

Your first data class

Compare a hand-written class with its data class twin:

Python Hand-written vs @dataclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each line like name: str inside the class body declares a field. The decorator reads those annotations, in order, and builds the special methods you learned about in Special (Dunder) Methods. The result is the same behavior with a fraction of the code.

Note: The type hints are required to declare fields, but Python doesn't check them at runtime. Product("Mug", "cheap", 40) works without complaint. Tools like mypy catch such mistakes before you run the code.

Default values

Give a field a default with =. As with function parameters, fields with defaults must come after fields without them:

Python Defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Mutable defaults need field(default_factory=...)

Remember the mutable default pitfall with function arguments? Data classes protect you from it: a list, dict or set default raises an error. Use field(default_factory=...) instead, which calls a function to make a fresh value for every object:

Python default_factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

default_factory takes any zero-argument callable: list, dict, set, date.today, or your own function or lambda.

Customizing fields with field()

field() has more options. The most useful are:

  • repr=False hides a field from __repr__ (handy for passwords or huge data).
  • compare=False leaves a field out of == and ordering.
  • init=False removes it from __init__; you then set it yourself, usually in __post_init__.

Extra setup with __post_init__

The generated __init__ only stores the values. If you need validation or computed fields, define __post_init__. The generated __init__ calls it right after setting the fields:

Python __post_init__

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line fails on purpose to show the validation. Notice that password doesn't appear in the output, and username isn't an __init__ parameter: it's derived from the email.

Frozen data classes

Pass frozen=True to make instances immutable. Assigning to a field raises FrozenInstanceError. Frozen data classes are also hashable, so you can use them in sets and as dictionary keys:

Python frozen=True

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

dataclasses.replace() builds a copy with some fields changed, which is the normal way to "update" an immutable object. Use frozen classes for values that shouldn't change: coordinates, money amounts, settings, dictionary keys. The last line fails on purpose.

Ordering and other options

With order=True, the data class also gets <, <=, > and >=. It compares fields as a tuple, in the order you declared them, so put the most important field first:

Python order=True

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few more decorator options you'll see in real code:

Option Effect
frozen=True instances can't be changed; they become hashable
order=True adds <, <=, >, >= based on fields in order
slots=True uses __slots__: less memory per object, slightly faster attribute access, no new attributes at runtime
kw_only=True all fields must be passed by keyword

You can also convert instances to plain dictionaries or tuples with asdict() and astuple(), which is perfect for saving as JSON:

Python
from dataclasses import asdict
import json

print(json.dumps(asdict(Product("Mug", 8.5, 40))))
# {"name": "Mug", "price": 8.5, "stock": 40}

Methods, properties and inheritance

A data class is still a normal class. You can add methods, properties, class methods and even your own __repr__; the decorator only writes a method if you haven't defined it yourself. That makes data classes a great home for small behaviors that belong with the data, such as a total property on an order or a from_dict alternative constructor.

Data classes can also inherit from other data classes. The child's fields are added after the parent's fields, in order, so the usual rule still applies: once a parent field has a default, every field after it, including the child's, needs a default too. kw_only=True is a neat way around that rule, because keyword-only fields can appear in any order.

One thing to keep in mind about mutability: with the default settings, data class instances are not hashable (the generated __eq__ disables hashing), so you can't put them in sets or use them as dictionary keys. That's deliberate. A mutable object whose hash changed while it sat in a set would get lost. If you need hashable instances, make the class frozen.

Data classes vs other options

Python has several ways to bundle data. A quick guide:

  • @dataclass: the default choice for a class whose main job is holding data, especially if it also needs methods.
  • typing.NamedTuple or collections.namedtuple: immutable, tuple-like records that also unpack and index like tuples. See collections.
  • A plain dict: fine for quick, loosely shaped data, but there's no fixed set of fields and typos in keys go unnoticed.
  • A regular class: when the object is mostly behavior rather than data, or needs a custom __init__.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which methods does a plain @dataclass generate by default?

    Ordering methods need order=True. Hashing comes automatically only with frozen=True.
  2. 2. How should you give a data class field an empty list as its default?

    default_factory creates a fresh list for every instance. A plain [] default raises a ValueError.
  3. 3. What does frozen=True do?

    Frozen instances raise FrozenInstanceError on assignment, and they get a __hash__ based on their fields.
  4. 4. Where do you put validation that should run when a data class is created?

    The generated __init__ calls __post_init__ right after storing the field values.

Summary

  • @dataclass turns annotated class attributes into fields and writes __init__, __repr__ and __eq__ for you.
  • Defaults use =; mutable defaults need field(default_factory=...).
  • field() options such as repr=False, compare=False and init=False fine-tune individual fields.
  • __post_init__ runs after the generated __init__, for validation and derived fields.
  • frozen=True makes immutable, hashable objects; use replace() to make changed copies.
  • order=True adds comparisons; slots=True and kw_only=True are useful extras; asdict() converts to a dictionary.

Next: Abstract Classes and Protocols, where you'll define interfaces that other classes must follow.