top | item 12323960

(no title)

ferrari8608 | 9 years ago

It's much simpler to me. Tuples are used when you need a sequence but don't need to modify the contents, for instance returning multiple objects from a function call. Lists are used when you want to add things to it.

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.

discuss

order

shoo|9 years ago

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.

sago|9 years ago

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.