A dataclass decorator in Python is a handy feature introduced in Python 3.7 to simplify the process of creating classes that primarily store data. The decorator generates boilerplate code, like init, repr, eq, and other special methods, making code more concise and readable. Essentially, using dataclasses simplifies the process of creating classes. In this post, I demonstrate its benefit with examples (full code and interactive execution).

Reasons to Use dataclass:
- Boilerplate code: It auto-generates methods like __init__, __repr__, and __eq__, saving extra typing of repetitive code.
- Better readability, easier to maintain: The class definitions become cleaner and easier to read, keeps the codebase clean and maintainable.
- Immutability: We can create immutable instances by setting frozen=True in the decorator.
- Built-in type checking: Helps enforce data type constraints by using type annotations.
In our example below, I will demonstrate that the @dataclass decorator automatically adds:
__init__,
methods to a class.
__repr__,
__eq__
These “magic methods” or “dunder methods” (short for “double underscore method”) are critical to dealing with classes and objects in Python. Without dataclass decorator, we’d have to implement our own code for the above methods for every class. __init_ method is used for instantiating an object and we would need to define each attribute (field) of the class and implement their behavior when an object is instantiated. This is done with the prefix self. followed by the attribute name and assigning the right parameter value to it. The __repr__ method is a special method that get called when we try to print the details of an object. The eq method defines how two instances of the class are compared for equality.
Without using dataclass, we would have to write our implementation to those in order to initialize and object with correct values, print its details, and check for objects’ equality. Look at the code below where the first definition of Book class is implemented without using dataclass decorator. Notice how each of these dunder methods are also implemented manually.
As you scroll down the code (in the left pane), you’ll find the same object ‘Book’ implemented using dataclass decorator. We no longer have to implement our own dunder methods. All we have to do is import dataclass add a line @dataclass (see code above), and use data type hints for each attribute or field: title, author, year, isbn.
Even without implementing our own __repr__ method, we can simply call print(book1) for example and it prints out the details of our object. Additionally, we check equality by comparing different objects without even writing any code for __eq__ method and it correctly returns True or False. If all attributes are the same between two objects, a simple line of code as: object1=object2 returns True. But if any of their attributes differ, it’ll return False. That’s exactly what we in the code above. Go ahead and run the code by clicking on Run icon and take a look at the output in the right pane. You’ll notice that with or without using the dataclass decorator we get identical outputs, but with less code and better readability!
Then there’s the optional benefit of adding immutability to our object. If we create an object, we can make it un-editable, even by code thereby freezing its attributes and values after the initial creation. To do so, all have to do is set frozen=True in the decorator. See the code example below. When you run it you’ll get an Error raised from Python saying “cannot assign to field ‘author'” as the code tries to change the author field value in the object ‘abook’.
Using dataclass is a great way to keep your codebase clean and maintainable, especially when dealing with a lot of data-centric classes.
I hope you found this post helpful and interesting. Explore this site for more tips and articles. Be sure to also check out my Patreon site where you can find free downloads and optional fee-based code and documentation. Thanks for visiting!
▛Interested in creating programmable, cool electronic gadgets? Give my newest book on Arduino a try: Hello Arduino!
Now, while I personally am not fond of repetitive underscores and self. phrases in the code, I don’t mind imagining singing along with this video substituting the word “thunder” with “dunder” 😉