Search⌘ K
AI Features

Dataclasses

Explore how dataclasses in Python 3.7 and later allow you to define objects with less boilerplate, offering benefits like automatic __init__, string representation, equality checking, and optional ordering or immutability. Understand when to use frozen dataclasses versus other structures and how to leverage these features in your coding.

We'll cover the following...

Since Python 3.7, dataclasses let us define ordinary objects with a clean syntax for specifying attributes. They look very similar to named tuples. This is a pleasant approach that makes it easy to understand how they work.

Example

Here’s a dataclass version of our Stock example:

Python 3.10.4
from dataclasses import dataclass
@dataclass
class Stock:
symbol: str
current: float
high: float
low: float

For this case, the definition is nearly identical to the NamedTuple definition. The dataclass function is applied as a class decorator, using the @ operator. This class definition syntax isn’t much less verbose than an ordinary class with __init__(), but it gives us access to several additional dataclass features.

It’s important to recognize that the names are provided at the class level but are not actually creating class-level attributes. The class-level names are used to build several methods, including the __init__() method; each instance will have the expected attributes. The ...