0Pricing
Python Academy · Lesson

Defining a Dataclass

Use @dataclass to remove boilerplate.

Why Dataclasses?

When you write a class that mostly holds data, you end up repeating the same boilerplate: an __init__, a __repr__, and an __eq__. The dataclasses module generates all of that for you from simple field declarations.

  • Less code to write and read.
  • Fewer chances for typos in __init__.
  • Built into the standard library since Python 3.7.

The Old Way

Here is a plain class that stores a point. Notice how much typing it takes just to store two numbers.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(1, 2)
print(p.x, p.y)

All lessons in this course

  1. Defining a Dataclass
  2. Default Values and field()
  3. Frozen and Comparison Options
  4. The attrs Library
← Back to Python Academy