Data Classes in Python (dataclasses)


The dataclasses is a new module added in Python's standard library since version 3.7. It defines @dataclass decorator that automatically generates constructor magic method __init__(), string representation method __repr__(), the __eq__() method which overloads == operator (and a few more) for a user defined class.

The dataclass decorator has following signature

dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

All the arguments take a Boolean value indicating whether a respective magic method or methods will be automatically generated or not.

The 'init' argument is True by default. It will automatically generate __init__() method for the class.

Let us define Student class using dataclass decorator as follows

from dataclasses import dataclass

@dataclass
class Student(object):
   name : str
   age : int
   percent : float

The auto-generated __init__() method is like

def __init__(self, name: str, age: int, percent: float):
   self.name = name
   self.age = age
   self.percent = percent

If the class explicitly defines __init__() method, then init parameter is ignored.

The repr argument is true also by default. Hence __repr__() method will be generated automatically. The __repr__() is a formal string representation of object. If the class already defines __repr__(), this parameter is ignored.

The eq argument is by default true . This will auto-generate the __eq__() method. This method gets called in response to equals comparison operator (==). Again, if the class already defines __eq__(), this parameter is ignored.

If the 'order' parameter is true (the default is False), the magic methods for comparison, __lt__(), __le__(), __gt__(), and __ge__() methods will beauto- generated, they implement comparison operators < <= > ans >= respectively. If order is true and eq is false, a ValueError is raised. If the class already defines any ofthese methods), it reults into TypeError.

unsafe_hash argument if False (the default), a __hash__() method is generated according to how eq and frozen are set.

frozen argument: If true (the default is False), emulates read-only frozen instances.

>>> from data_class import Student
>>> s1=Student('Naveen', 21, 50.50)
>>> s2=Student('Mangesh', 20, 50.00)
>>> s1==s2
False

asdict()

This function converts class instance into a dictionary object.

>>> import dataclasses
>>> dataclasses.asdict(s1)
{'name': 'Naveen', 'age': 21, 'percent': 50.5}

astuple()

This function converts class instance into a tuple object.

>>> dataclasses.astuple(s2)
('Mahesh', 20, 50.0)

make_dataclass()

This function creates a new dataclass from the list of tuples given as fields argument.

>>> NewClass=dataclasses.make_dataclass('NewClass', [('x',int),('y',float)])
>>> n = NewClass(10,20)
>>> n
NewClass(x=10, y=20)

Updated on: 30-Jul-2019

536 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements