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.
Here's a dataclass
version of our Stock
example:
>>> 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. We encountered decorators in Chapter 6, Abstract Base Classes and Operator Overloading. We'll dig into them deeply in Chapter 11, Common Design Patterns. This class definition syntax isn't much less verbose than an ordinary class with __init__()
, but it gives us access to several additional dataclass...