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="user1@example.com")
A new feature required the possibility of changing the value. As you probably now, the namedtuple
is immutable, we can’t change any value.
>>> user1.email = "user2@example.com"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
@dataclassclass User: id: int name: str email: str
user1 = User(id=1, name="User1", "email"="user1@example.com")
Now, it’s possible to change the value.
>>> user1.email = "user2@example.com">>> user1.email'user2@example.com
Of course, that’s not all that data classes offer!