[Python-ideas] namedtuple fields with default values

Antony Lee antony.lee at berkeley.edu
Fri Jul 17 18:21:20 CEST 2015


The problem of subclassing is the somewhat tedious repetition in the
argument list of __new__.  You can abuse the fact that function definition
allows you to
1. create an object who knows its name and
2. list arguments, with or without default values
to write a decorator @Namedtuple, such that

@Namedtuple
def Record(foo, bar=default): pass

(I have an implementation but it's nothing really special, just
introspecting the signature object.)

Antony

2015-07-17 8:33 GMT-07:00 Antoine Pitrou <solipsis at pitrou.net>:

> On Fri, 17 Jul 2015 10:44:15 -0400
> Barry Warsaw <barry at python.org> wrote:
> >
> > I don't know about "Pythonic" but there's a not too horrible way to do
> it:
> >
> > _Record = namedtuple('Record', 'url destination checksum')('', '', '')
> >
> > def Record(url, destination, checksum=''):
> >     return _Record._replace(
> >         url=url, destination=destination, checksum=checksum)
>
> My usual pattern is to subclass the namedtuple class and override the
> constructor (especially if I want to add behaviour):
>
> class Record(namedtuple('_Record', ('url', 'dest', 'checksum'))):
>     __slots__ = ()
>
>     def __new__(...): #etc
>
>
> Regards
>
> Antoine.
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150717/9607ff28/attachment.html>


More information about the Python-ideas mailing list