Python dataclass Decorator, the new “default”
If you know a bit about object-oriented programming, you for sure try and look in a new language on how to create the initializer or constructor.
This is the default behavior when constructing objects, and, with some languages, this can be verbose or simple.
The truth is, with Python this was/is verbose, until now, we have a better way to keep things cleaner without losing functionality.
What will this ‘dataclass’ improve or replace?
Glad that you asked, so first let’s just check one small code, let’s create one class, and inside this class, we will have some variables that are needed in order to create this object, and our class example will be about a “house”.
class House():
def __init__(self, owner, residents, rooms, garage):
self.owner = owner
self.residents = residents
self.rooms = rooms
self.garage = garage
def __eq__(self, o: object) -> bool:
if isinstance(o, House):
return (self.owner == o.owner and
self.residents == o.residents and
self.rooms == o.rooms and
self.garage == o.garage)
return False
Nice, now we have an object, with an implementation of the “constructor” or initializer, expecting some parameters.
Also, as we want to compare this object, to know if when creating other objects their content is the same I also implemented (override) the equitable method.
And testing it this is the result:
It does work how to expect, so nothing new here, and this would be your normal implementation and way to do it.
Dataclass for the win!
Now that we clearly see the problem, let’s improve and use the dataclass Decorator to completely transform our code, this is the output.
from dataclasses import dataclass
@dataclass
class House():
owner: str
residents: int
rooms: int
garage: int
Well, we can notice the huge difference right? Not only we did not have to implement the initializer method, which was to set the same attribute name to its class variable representation, but we also did not have to implement the equatable method.
And not only this, but we also improved our code by typing it, this will improve how our data inside our code is handled, to avoid using the wrong type.
The basic rule to use dataclass is, the types need to have a type. Python will use the fields with types to “generate” automatically the necessary constructor for it.
Not only do these functionalities come as default, we just checked the automatic constructor creation and the comparison method.
And what about the string representation of the object? With dataclass this also become automatically:
The previous code version did not have it, this is how it looks:
You know now how this resource can improve and speed up your coding while creating Python classes.
Important to notice that this is only available from Python version 3.7 and higher.
If you want to know a bit more about it you can check this official link: https://docs.python.org/3/library/dataclasses.html.
Conclusion
I hope you enjoyed reading this. If you’d like to support me as a writer, consider signing up to become a Medium member. It’s just $5 a month and you get unlimited access to Medium also if you liked, consider sharing with others that also want to learn more about this.
Also, I started a new channel on YouTube, I want to teach in videos what I write about, so please, subscribe if you liked this tutorial.
Youtube channel:
Linkedin:
Instagram: @thedevproject