Data classes in Python

Posted by Afsal on 08-Mar-2024

Hi Pythonistas!

Today we are learning about dataclasses in Python. Data classes were introduced in Python 3.7 to simplify the creation of classes primarily used to store data. They automatically generate special methods like __init__(), __repr__(), and others, based on the class attributes. Let us learn with an example

Code

>>> from dataclasses import dataclass
>>>
>>> @dataclass
    class User:
        username: str
        password: str
        email: str
>>> u = User(username="afsal", password="********", email="afsal@parseltongue.co.in")
>>>
>>> u
User(username='afsal', password='********', email='afsal@parseltongue.co.in')
>>> u.username
'afsal'
>>> u.password
'********'
>>> u.email
'afsal@parseltongue.co.in'
>>> print(type(u))
<class '__main__.User'>
>>>

By default the dataclasses are mutable.

>>> u.username = "afsals"
>>> u
User(username='afsals', password='********', email='afsal@parseltongue.co.in')
>>>

We can make it immutable using frozen=True in the dataclass decorator

>>> @dataclass(frozen=True)
    class ImmutableUser:
        username: str
        password: str
        email: str
>>> iu = ImmutableUser(username="afsal", password="******", email="afsal@parseltongue.co.in")
>>> iu
ImmutableUser(username='afsal', password='******', email='afsal@parseltongue.co.in')
>>> iu.username = "afsals"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'username'
>>>

Dataclasses are useful when

  • Configuration objects
  • Data storage
  • API response and Json parsing
  • ORM models etc

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in