Hacker News new | past | comments | ask | show | jobs | submit login

namedtuple is a reasonable way to define a new value type in python. unfortunately the very easy way to define a new type in python is to use `class`, which brings with it a bunch of behaviour that you often don't want or need: comparison by identity rather than comparison by equality, no default support for repr, no default support for ordering, mutability, support for inheritance, etc

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.




First para: I think maybe you're confusing 'class' with inheritance from 'object'. A good tip is to do:

    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.


I would also add

    __slots__ = ()
to your class definition so that instances of Foo keep the small memory footprint benefits do namedtuple.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: