8.2 Dataclasses
Since Python 3.7, dataclasses let us define ordinary objects with a clean syntax for specifying attributes. They look – superficially – very similar to named tuples. This is a pleasant approach that makes it easy to understand how they work. For more details, see Modern Python Cookbook, Chapter 7 for recipes related to dataclasses.
Here’s a dataclass version of our Stock example:
from decimal import Decimal
from dataclasses import dataclass
@dataclass
class Stock:
symbol: str
current: Decimal
high: Decimal
low: Decimal
For this case, the definition is nearly identical to the NamedTuple definition.
The @dataclass decorator transforms the given code into a more complete class. We encountered decorators in Chapter 6. We’ll dig into them deeply in Chapter 11.
As with NamedTuple, it’...