Differences creating tuples and collections.namedtuples
John Reid
johnbaronreid at gmail.com
Mon Feb 18 06:47:35 EST 2013
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])
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.
More information about the Python-list
mailing list