by ferrari8608 · 10y ago · 0 comments
Namedtuples are wonderful! It's like a class with only attributes, except you don't have to define a new class and get slapped across the back of your head by more experienced programmers for creating a useless class. Access objects by index, by name, or by iteration. It's very versatile.
that said, writing generic code that works transparently with both namedtuple values and objects can be a bit irritating: e.g. you might want to derive a new value/object from an existing value/object that updates one of the attributes of the value/object.
class Foo(namedtuple('Foo', (...)):
def __repr__(self):
...
Your 'Foo' gets ordering, hashing, comparison, because it derives from 'namedtuple'. It gets '__repr__' too, but in the example I'm overriding that. __slots__ = ()
to your class definition so that instances of Foo keep the small memory footprint benefits do namedtuple.