Differences creating tuples and collections.namedtuples

raymond.hettinger at gmail.com raymond.hettinger at gmail.com
Tue Feb 19 08:48:46 CET 2013

On Monday, February 18, 2013 6:09:16 AM UTC-8, John Reid wrote:
> I'm aware how to construct the namedtuple and the tuple. My point was
> that they use different syntaxes for the same operation and this seems
> to break ipython. I was wondering if this is a necessary design feature
> or perhaps just an oversight on the part of the namedtuple author or
> ipython developers.

It was not an oversight on the part of the namedtuple author.
It was a deliberate design decision to improve usability for
named tuple's primary use case.

Consider a namedtuple such as:

     Person = namedtuple('Person', ['name', 'rank', 'serial_number'])

With the current signature, instances can be created like this:

    p = Person('Guido', 'BDFL', 1)

If instead, the __new__ signature matched that of regular tuples,
you would need to write:

   p = Person(('Guido', 'BDFL', 1))

The double parens are awkward.  You would lose tooltips that prompt you for Person(name, rank, serial_number).  You would lose the ability to use keyword arguments such as Person(rank='BDFL', serial_number=1, name='Guido') or Person(**d).  The repr for the namedtuple would lose its eval(repr(t)) roundtrip property.  

If your starting point is an existing iterable such as s=['Guido', 'BDFL', 1], you have a couple of choices:   p=Person(*s) or p=Person._make(s).  The latter form was put it to help avoid unpacking and repacking the arguments.   


More information about the Python-list mailing list