Python 3.7 - @dataclass

July 28, 2019 - IT

Suppose I had a piece of code like that.

import collections

User = collections.namedtuple("User", ("id", "name", "email"))
user1 = User(id=1, name="User1", email="[email protected]")

A new feature required the possibility of changing the value. As you probably now, the namedtuple is immutable, we can't change any value.

>>> = "[email protected]"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

Fortunately, Python 3.7 came to the rescue!

Python 3.7 has a new feature, dataclasses. Using @dataclass decorator, I was able to remove namedtuple and modify my data without any issues.

from dataclasses import dataclass

class User:
    id: int
    name: str
    email: str

user1 = User(id=1, name="User1", "email"="[email protected]")

Now, it's possible to change the value.

>>> = "[email protected]"
'[email protected].com

Of course, that's not all that data classes offer!