3 ms·
I strongly dislike namedtuple. It's such an attractive nuisance. So many people use it (pre-Python 3.7's data classes) as a lightweight mechanism for class crea
by eesmith 7y ago
I strongly dislike namedtuple. It's such an attractive nuisance. So many people use it (pre-Python 3.7's data classes) as a lightweight mechanism for class creation.
But doing that causes it to inherit tuple behavior even when that's inappropriate for light-weight classes. Consider the example here:
>>> from collections import namedtuple
>>> Person = namedtuple("Person", "name age sex")
>>> person1 = Person("Rakesh", 24, "male")
Because it's a tuple, people can extract the fields like this:
name, age, sex = person1
or
sex = person1[-1]
Now, later on you add a new field for "title". It seems like the following should work:
>>> Person = namedtuple("Person", "name age sex title")
However, it will break many places which used tuple destructuring/unpacking to access the fields.
In essence, when you used namedtuple, you implicitly make some API promises that you probably didn't mean to make.