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.
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 = True
argument in the dataclass.
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 )
Here’s a line-by-line description of the code above:
Line 1: We import dataclass
form the dataclasses
module.
Lines 3–7: We create a Student
dataclass containing name
, roll_no
, and enroll
attributes. We add the eq = True
and frozen = True
arguments for letting the dataclass generate the __hash__()
method by default in this class and the order = True
argument to make comparisons between instances.
Lines 9–12: We created the instances of Student
dataclass. 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 s3
and s4
instances of the dataclass.
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.
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