Data Classes
Last monthly, in my article covering the concept of static polymorphism in python, I mentioned the Data classes.
Introduced with python 3.7, DataClasses are python classes that facilitate the storage of data.
Those classes help decouple the data storage from the data logic while handling many boilerplate actions behind the scene(more details later).
This new concept is available via the dataclass function(class decorator) within the module dataclasses. This class decorator has two forms:
The simple form where @dataclass is defined without any parentheses and parameters will automatically enrich your class with the following “dunder” methods: __init__ ,‘__repr__ and __eq__.
The second form, where @dataclass is defined with parentheses, allowed you to decide which “dunber” methods will be supported by default. For more details, see here.
In the first example below, we use a python class to create a data storage for all the securities in our portfolio.
As you can see, this code is quite lengthy.
Now, let’s used the dataclass decorator.
The above implementation is more concise and will automatically provide the __init__, __repr__ and __eq__ “dunder” methods.
This is quite cool, right?
I will confess that I have not been using any dataclasses within any of the production-grade code, but I am planning to do so in a near future !!!
So, please have a go with those data classes, and do let me know your thoughts.