Python Data Class Parameters / Parameterized Data class

Python Data Class Parameters
Share this blog with others!
  • 7
    Shares

In the previous blog, we learned about data class in python, its syntax and the built in-functions like replace and make. This time we will dive a bit deeper and understand what parameters the data class takes (The Parameterized Data Class in Python).

Python Data Class Parameters

The below code is the function definition of the dataclass in python.

def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False):

There are six optional parameters that python data class takes:

  1. init
  2. repr
  3. eq
  4. order
  5. unsafe_hash
  6. frozen

we will learn about these parameters one by one.

Init Parameter in Python Data Class

This is the first optional parameter in the python data class and is set to True by default. This creates the initialization function for the class with the class attributes.

Example:

@dataclass
class Student():
    name: str
    clss: int
    stu_id: int

In the above code we used dataclass decorator and thus just declared the class attributes with type hint.

When the init parameter is set to default i.e True. The code is converted to simple class with the init function defined.

class Student():
    def __init__(self,name,clss,stu_id):
        self.name = name
        self.clss = clss
        self.stu_id = stu_id

We can access the class attributes.

Example:

student = Student('HTD', 10, 17)

>>> print(student.name)

HTD

>>> print(student.clss)

10

>>> print(student.stu_id)

17

Now let’s make the init parameter as false and see the effect.

@dataclass(init=False)
class Student():
    name: str
    clss: int
    stu_id: int


>>> student = Student('HTD', 10, 17)

Traceback (most recent call last):
  File ".\main.py", line 11, in <module>
    student = Student('HTD', 10, 17)   
TypeError: Student() takes no arguments

When there is no init function in a class this means there are no class attributes and thus the Student class doesn’t take any arguments.

Python Data Class repr Parameter

The repr parameter provides the representation of the class. If set to False, the class object will return its memory address.

Learn how the __repr__ method is overridden from the python dataclass blog.

When repr is set to True (default):

@dataclass()
class Student():
    name: str
    clss: int
    stu_id: int


student = Student('HTD', 10, 17)

>>> print(student)

Student(name='HTD', clss=10, stu_id=17)

When repr is set to False:

@dataclass(repr=False)
class Student():
    name: str
    clss: int
    stu_id: int


student = Student('HTD', 10, 17)

>>> print(student)

<__main__.Student object at 0x000001DD41502940>

Data Class Eq Parameter

The eq parameter is for equality check between objects of the class. If set to False, the equality check will not work for objects of the class.

When eq is set to True(Default):

@dataclass()
class Student():
    name: str
    clss: int
    stu_id: int


student1 = Student('HTD', 10, 17)
student2 = Student('HTD', 10, 17)


>>> print(student1 == student2)

True

when eq is set to False:

@dataclass(eq=False)
class Student():
    name: str
    clss: int
    stu_id: int


student1 = Student('HTD', 10, 17)
student2 = Student('HTD', 10, 17)


>>> print(student1 == student2)

False

For further reference, must read the previous blog on python dataclasses introduction.

Order Parameter in Python Data Class

The order parameter helps us to implement the relational operators on the objects of the class.

Order Parameter is set to False by default.

Let’s understand this by an example:

student1 = Student('HTD', 10, 17)
student2 = Student('Arpit', 10, 12)


>>> print(student1 > student2)

Traceback (most recent call last):
  File ".\main.py", line 15, in <module>
    print(student1 > student2)
TypeError: '>' not supported between instances of 'Student' and 'Student'

When the order parameter is set to False(Default). we are not able to compare the two objects.

Let’s set the order parameter to True:

@dataclass(order=True)
class Student():
    name: str
    clss: int
    stu_id: int


student1 = Student('HTD', 10, 17)
student2 = Student('Arpit', 10, 12)


>>> print(student1 > student2)

True

>>> print(student1 < student2)

False

unsafe_hash parameter

In python, hash is calculated only for immutable objects, and the object of a class is mutable, so the hash can’t be calculated.

But, when unsafe_hash parameter in data class is set to True, the hash can be generated for the object (on developer’s risk, that’s why its unsafe_hash).

Let’s understand it via example:

student = Student('HTD', 10, 17)


>>> print(hash(student))

Traceback (most recent call last):
  File ".\main.py", line 14, in <module>
    print(hash(student))
TypeError: unhashable type: 'Student'

Set the unsafe_hash parameter to True:

@dataclass(unsafe_hash=True)
class Student():
    name: str
    clss: int
    stu_id: int


student = Student('HTD', 10, 17)


>>> print(hash(student))

5263561900058177456

Python Data Class Frozen Parameter

By Default the object of a class is mutable, if you want to make your class object immutable, set the Frozen parameter as True.

Example:

student = Student('HTD', 10, 17)
student.name = 'Arpit Sahu'


>>> print(student)

Student(name='Arpit Sahu', clss=10, stu_id=17)

Let’s do the same but this time the frozen parameter will be set to True.

@dataclass(frozen=True)
class Student():
    name: str
    clss: int
    stu_id: int


student = Student('HTD', 10, 17)


>>> student.name = 'Arpit Sahu'

Traceback (most recent call last):

    student.name = 'Arpit Sahu'
  File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'name'

This makes the class object immutable.

As discussed in the earlier section(unsafe_hash), the hash is always generated for the immutable object. when we set the frozen parameter to True, it makes our class object immutable, and thus hash can be generated, even without setting the unsafe_hash to True.

@dataclass(frozen=True)
class Student():
    name: str
    clss: int
    stu_id: int


student = Student('HTD', 10, 17)

>>> print(hash(student))

-2769945671446176732

Hash of two same class objects is the same

student1 = Student('HTD', 10, 17)
student2 = Student('HTD', 10, 17)

>>> print(hash(student1), hash(student2))

-1905686657676437369 -1905686657676437369

>>> print(hash(student1) == hash(student2))

True

Hope you like it!

Learn more about python data class parameters from the official documentation.


Share this blog with others!
  • 7
    Shares

Leave a Comment

Your email address will not be published. Required fields are marked *