Re:Namedtuple in a Post-Dataclasses World
by masklinn on Wednesday July 21, 2021 @12:10PM
(#27908120)
Well in and of itself none, in the sense that anything a namedtuple can do you could do by hand (it really just defines a class). However namedtuple:
* extends tuples, so a namedtuple is literally a tuple (which is useful)
* sets up a bunch of properties for the "named fields", which are basically just names on the tuple elements
* sets up a few other utility methods e.g. nice formatting, `_make`, `_asdict`, `_replace`
Now the latter two are nice, and mostly replicated by dataclasses (or attrs). The first one is the raison d'être of namedtuples though: originally their purpose is to "upgrade" tuple return values into richer / clearer types e.g. urlparse originally returned a 6-utple which is not necessarily super wieldy / clear, you can probably infer that the 3rd element is the path but… after upgrading to namedtuple it's just `result.path which is usually much clearer.
And because namedtuples are still classes in and of themselves, you can inherit from them to create a class with a `__dict__` with relative ease.
* extends tuples, so a namedtuple is literally a tuple (which is useful)
* sets up a bunch of properties for the "named fields", which are basically just names on the tuple elements
* sets up a few other utility methods e.g. nice formatting, `_make`, `_asdict`, `_replace`
Now the latter two are nice, and mostly replicated by dataclasses (or attrs). The first one is the raison d'être of namedtuples though: originally their purpose is to "upgrade" tuple return values into richer / clearer types e.g. urlparse originally returned a 6-utple which is not necessarily super wieldy / clear, you can probably infer that the 3rd element is the path but… after upgrading to namedtuple it's just `result.path which is usually much clearer.
And because namedtuples are still classes in and of themselves, you can inherit from them to create a class with a `__dict__` with relative ease.