Using dataclasses

Before Python 3.7, namedtuple was the easiest way to use class-like objects without having to implement a class for each object with the associated constructor. Since Python 3.7, dataclasses can also be used for this purpose. dataclass allows a class to easily declare that it contains only data. This is available in the dataclasses module of the standard library. The same snippet can be written as follows with dataclasses:

from dataclasses import dataclass

@dataclass class Basket: count what

@dataclass class FruitCount: count double

obs = Observable.from_([Basket(count=5, what='apple'),
Basket(count=3, what='orange')])
.filter(lambda i: i.what == 'apple')
.map(lambda i: i.count)
.map(lamda i: FruitCount(count=i, double=i*2))
...

Compared to namedtuple, using dataclass is the same, but the definition is done as a class definition. If an application requires Python 3.7 at a minimum, then data classes can be used. However, named tuples still require less code to declare, and their immutability is a nice sanity check in functional code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.10.45