What are python dataclasses, and how do they work?
The dataclasses concept in Python was introduced in the Python 3.7 version to store data objects. Due to its immutability, it makes it an excellent choice for defining and managing data because it prevents undesired modifications to the object’s state. Once dataclass instances are initialized, their attributes cannot be changed, enhancing data integrity and predictability in the code.
Why do we need dataclasses?
There are several features that dataclasses offer us instead of the ordinary classes. Here’s a list of a few of them:
They provide immutability to the created objects as it is their default property.
They offer us various automatically generated methods, such as
__init,__hash__,__equal__, and__str__.They reduce the boilerplate code to a great extent, eventually enhancing the code readability.
They let us compare instances directly using
order = Trueargument in the dataclass.
Example
Here’s a coding implementation of dataclass, incorporating a few features that it provides us.
from dataclasses import dataclass@dataclass(eq = True, frozen = True, order = True)class Student:name: strroll_no: intenroll: bools1 = Student("Gini", 10, True)s2 = Student("Suzaine", 15, True)s3 = Student("Aryan", 8, True)s4 = Student("Aryan", 8, True)people = {s1: "Chemistry", s2: "Biology", s3: "Mathematics"}print(people[s3])print(s3 == s4 )print(s3 > s1 )
Explanation
Here’s a line-by-line description of the code above:
Line 1: We import
dataclassform thedataclassesmodule.Lines 3–7: We create a
Studentdataclass containingname,roll_no, andenrollattributes. We add theeq = Trueandfrozen = Truearguments for letting the dataclass generate the__hash__()method by default in this class and theorder = Trueargument to make comparisons between instances.Lines 9–12: We created the instances of
Studentdataclass. Notice that we didn’t create the__init__()method in the class, but the dataclass allows us to create its instances automatically.Line 14: We use instances as keys to generate a hash.
Line 15: We access the created hash value based on instances.
Lines 16–17: We make comparisons between the
s3ands4instances of the dataclass.
Conclusion
Python dataclasses are a successful and effective approach to interacting with data objects, making them immutable and enabling automatic creation to construct useful functions. It is a useful method for getting rid of redundant code while also making the code more stable and readable. These characteristics make it easier for developers to create apps that are better and easier to maintain.
Quiz yourself
Which is a key benefit of using dataclasses?
They increase the complexity of the code.
They allow for runtime type checking.
They provide immutability to created objects.
They require more boilerplate code.
Free Resources