Thanks to visit codestin.com
Credit goes to www.pythonmorsels.com

What are dataclasses? PREMIUM

Series: Dataclasses
Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
3 min. read Watch as video Python 3.10—3.14
Python Morsels
Watch as video
02:56

Dataclasses are a way to make friendly classes in Python while avoiding common boilerplate code.

How do dataclasses work?

This is a dataclass:

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

That x: float and y: float syntax is called type hinting or type annotations.

That @ symbol is called the decorator syntax.

Python's decorators can change the behavior of the functions or classes that they decorate.

We've decorated our Point class with the dataclass decorator from Python's dataclasses module.

The dataclass decorator reads the type annotations that we've defined on our class, to automatically allow our class to accept certain arguments.

So this Point class can be called with two arguments to create a two-dimensional point:

>>> p = Point(1, 2)

The resulting Point object has an x attribute and a y attribute:

>>> p.x
1
>>> p.y
2

And it has a friendly string representation:

>>> p
Point(x=1, y=2)

You can even compare two Point objects to see whether they have the same x and y values:

>>> p == Point(1, 2)
True
>>> p == Point(1, 3)
False

All of this works thanks to the dataclass decorator on our class.

Dataclasses versus regular classes

If we wanted to create the same class without using the dataclass decorator, we could create a class with three methods:

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

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

    def __eq__(self, other):
        if not isinstance(other, Point):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

These methods control our class's initialization, its string representation, and how it determines whether it's equal to other objects.

This works, but it's quite a bit of boilerplate code for a very simple class.

That's the beauty of the dataclass decorator. The dataclass decorator is simply a helper for making classes quickly and easily.

Making a dataclass

Let's make a simple dataclass that has just the default functionality and nothing more.

To start, we'll import the dataclass decorator from Python's dataclasses module:

from dataclasses import dataclass

We'll make a dataclass that represents financial transactions, so we'll call our class Transfer:

@dataclass
class Transfer:
    ...

We've decorated our Transfer class with the dataclass decorator. Now we'll need to specify the fields within our class.

Our dataclass fields are specified using type annotations, so each field needs a data type.

Transfer objects will have a sender (string), a receiver (string), an amount (number), and a memo field (string).

@dataclass
class Transfer:
    sender: str
    receiver: str
    amount: float
    memo: str

We've just created a dataclass!

We can create a new instance of this dataclass by passing in those four values, either as positional arguments or as keyword arguments:

>>> t1 = Transfer("Alice", "Bob", 20.0, "Lunch")
>>> t2 = Transfer(sender="Alice", receiver="Bob", amount=20.0, memo="Lunch")

Each instance of this class will have sender, receiver, amount, and memo attributes:

>>> t1.amount
20.0
>>> t1.memo
'Lunch'

Each instance will also have a friendly string representation that shows each of these attributes:

>>> t1
Transfer(sender='Alice', receiver='Bob', amount=20.0, memo='Lunch')

We can also compare instances of this Transfer class for equality:

>>> t1 == t2
True

Dataclasses simplify class creation

Dataclasses can be a pretty useful helper for making a simple class.

We've just touched on the basics of dataclasses here. We'll look at more advanced features another time.

Python Morsels
Watch as video
02:56
This is a free preview of a premium screencast. You have 2 previews remaining.