Differences creating tuples and collections.namedtuples

Dave Angel davea at davea.name
Mon Feb 18 07:11:24 EST 2013


On 02/18/2013 06:47 AM, John Reid wrote:
> Hi,
>
> I was hoping namedtuples could be used as replacements for tuples in all instances. There seem to be some differences between how tuples and namedtuples are created. For example with a tuple I can do:
>
> a=tuple([1,2,3])
>
> with namedtuples I get a TypeError:
>
> from collections import namedtuple
> B=namedtuple('B', 'x y z')
> b=B([1,2,3])

You are passing a single list to the constructor, but you specified that 
the namedtuple was to have 3 items.  So you need two more.

>
> TypeError: __new__() takes exactly 4 arguments (2 given)
>> <ipython-input-23-d1da2ef851fb>(3)<module>()
>        1 from collections import namedtuple
>        2 B=namedtuple('B', 'x y z')
> ----> 3 b=B([1,2,3])
>
> I'm seeing this problem because of the following code in IPython:
>
> def canSequence(obj):
>      if isinstance(obj, (list, tuple)):
>          t = type(obj)
>          return t([can(i) for i in obj])
>      else:
>          return obj
>
> where obj is a namedtuple and t([can(i) for i in obj]) fails with the TypeError. See http://article.gmane.org/gmane.comp.python.ipython.user/10270 for more info.
>
> Is this a problem with namedtuples, ipython or just a feature?
>
> Thanks,
> John.
>

If you want one item (list or tuple) to act like 3 separate arguments, 
you could use the "*" operator:

b = B( *[1,2,3] )

or in your canSequence function, if you want a namedTuple
           return t(*[can(i) for i in obj])



-- 
DaveA



More information about the Python-list mailing list