Movatterモバイル変換


[0]ホーム

URL:


[Python-ideas] namedtuple fields with default values

Barry Warsawbarry at python.org
Fri Jul 17 16:44:15 CEST 2015


On Jul 16, 2015, at 01:03 PM, Russell Kaplan wrote:>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.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)Now you only need to provide 'url', and 'destination' when you create aRecord.  Okay, sure _Record is the actual namedtuple, but I usually don'tcare.>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'])That would mean you couldn't ever have an actual parameter called'optional_bar'.>This suggestion is fully backwards compatible and allows for cleaner>definitions of nametuples with default-value fields. Thanks for considering.Not that I think anything really needs to be done, but a few other approachescould be:* Allow for arbitrary keyword arguments at the end of the signature to define  default values.  Record = namedtuple('Record', 'url destination checksum', checksum='')* Extend the semantics of field_names to allow for a dictionary of attributes  mapping to their default values, though you'd need a marker to be able to  specify a required field:  Record = namedtuple('Record', dict(url=Required, destination=Required,                                     checksum=''))I suppose I'd prefer the former, although that might cut off the ability toadd other controlling arguments to the namedtuple() API.Cheers,-Barry-------------- next part --------------A non-text attachment was scrubbed...Name: not availableType: application/pgp-signatureSize: 819 bytesDesc: OpenPGP digital signatureURL: <http://mail.python.org/pipermail/python-ideas/attachments/20150717/0cb379f6/attachment.sig>


More information about the Python-ideasmailing list

[8]ページ先頭

©2009-2026 Movatter.jp