[issue8415] namedtuple vs tuple

H Krishnan report at bugs.python.org
Fri Apr 16 06:28:24 CEST 2010


New submission from H Krishnan <hetchkay at gmail.com>:

Named tuples and tuples have different creation behavior. Changing a tuple to a namedtuple will involve changing the usage as well. For example:

>>> ntuple = collections.namedtuple("ntuple", "a,b")
>>> ntuple(1,2)
ntuple(a=1, b=2)
>>> tuple(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: tuple() takes at most 1 argument (2 given)
>>> tuple([1,2])
(1, 2)
>>> ntuple([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 3 arguments (2 given)
>>>

Because of this, to create a tuple object given a 'tuple class', we need to do something like:
def makeTuple(tupleCls, *args):
   if hasattr(tupleCls, "_fields"):
      return tupleCls(*args)
   else:
      return tupleCls(args)

My suggestion: A namedtuple should also accept a single iterable as argument, in which case, the iterable will be broken up and assigned to individual fields.
This will break an existing behaviour of namedtuple: if only one field is present in the namedtuple and an iterable is passed to the namedtuple, that field is currently assigned the iterable. However, namedtuples are seldom used for single fields and so this may not be that important.

----------
components: None
messages: 103289
nosy: hkrishnan
severity: normal
status: open
title: namedtuple vs tuple
type: feature request
versions: Python 2.6

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue8415>
_______________________________________


More information about the Python-bugs-list mailing list