[Python-ideas] namedtuple fields with default values

Russell Kaplan russell.j.kaplan at gmail.com
Thu Jul 16 22:03:50 CEST 2015


I'm using a namedtuple to keep track of several fields, only some of which
ever need to be specified during instantiation. However, there is no
Pythonic way to create a namedtuple with fields that have default values.

>>> Foo = namedtuple('Foo', ['bar', 'optional_baz'])
>>> f = Foo('barValue') # Not passing an argument for every field will
cause a TypeError
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 3 arguments (2 given)

If you do want default parameters for a namedtuple, the workaround right
now involves modifying Foo.__new__'s defaults:
>>> Foo = namedtuple('Foo', ['bar', 'optional_baz'])
>>> Foo.__new__.__defaults__ = (None, None)

Then you can call Foo's constructor without specifying each field:
>>> f = Foo('barValue')
>>> f
Foo(bar='barValue', optional_baz=None)

Having to assign to Foo.__new__.__defaults__ is a bit ugly. I think it
would be easier and more readable to support syntax like:
>>> Foo = namedtuple('Foo', ['optional_bar=None', 'optional_baz=None'])

This suggestion is fully backwards compatible and allows for cleaner
definitions of nametuples with default-value fields. Thanks for considering.

Russell
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150716/e9b8312b/attachment.html>


More information about the Python-ideas mailing list