Python dataclass: Taking advantage of the new decorator
--
Introduction
Python 3.7 introduced a new and really interesting decorator called dataclass. Despite this decorator offers no new functionality, which means that it does not offer a new possibility to python developers in terms of implementation, it makes it way easier to define classes oriented to store data. Think of it like what we used to call “Plain Old JavaScript Objects” (aka POJOs) in Javascript. Classes that their role is mainly to store data and to contain minimal logic. Actually, there are no restrictions to how much or what kind of logic these classes can contain, however this is my personal design advice (and the way I believe this tool is designed to be used).
An example
As you may already understand from this simple example, an important aspect of dataclasses is that you get many functionalities “for free”, which means you do not have to implement them by hand. Functions like __init__
(class initializer), __repr__
(function returning a string representation of the class) and __eq__
(function to compare various instances with each other) are already implemented.
The notation and the syntax is simple: After you declare a class under the “@dataclass” decorator, then you simple declare the fields of your class along with there respective data type.
Default values
Dataclasses also provide the functionality to declare default values for fields if you want to. Below you can see an example of a dataclass with default values for the fields name and surname. Note that in case you do not want to set default values for all fields, the fields that have default values must be declared at the end of the fields list.