Movatterモバイル変換


[0]ホーム

URL:


[Python-Dev] setdefault's second argument

David Goodgergoodger at python.org
Tue Aug 30 22:24:44 CEST 2005


[Tim Peters]> Dang!  I may have just found a use, in Zope's> lib/python/docutils/parsers/rst/directives/images.py (which is part> of docutils, not really part of Zope):>>     figwidth = options.setdefault('figwidth')>     figclass = options.setdefault('figclass')>     del options['figwidth']>     del options['figclass']If a feature is available, it *will* eventually be used!Whose law is that?> I'm still thinking about what that's trying to do <0.5 wink>.The code needs to store the values of certain dict entries, thendelete them.  This is because the "options" dict is passed on toanother function, where those entries are not welcome.  The code aboveis simply shorter than this:    if options.has_key('figwidth'):        figwidth = options['figwidth']        del options['figwidth']    # again for 'figclass'Alternatively,    try:        figwidth = options['figwidth']        del options['figwidth']    except KeyError:        passIt saves between one line and three lines of code per entry.  Butsince those entries are probably not so common, it would actually befaster to use one of the above patterns.> Assuming options is a dict-like thingie, it probably meant to do:>>     figwidth = options.pop('figwidth', None)>     figclass = options.pop('figclass', None)Yes, but the "pop" method was only added in Python 2.3.  Docutilscurrently maintains compatibility with Python 2.1, so that's RIGHTOUT!> David, are you married to that bizarre use of setdefault <wink>?No, not at all.  In fact, I will vehemently deny that I ever wrotesuch code, and will continue to do so until someone looks up itshistory and proves that I'm guilty, which I probably am.--David Goodger <http://python.net/~goodger>-------------- next part --------------A non-text attachment was scrubbed...Name: signature.ascType: application/pgp-signatureSize: 253 bytesDesc: OpenPGP digital signatureUrl :http://mail.python.org/pipermail/python-dev/attachments/20050830/8588c318/signature.pgp


More information about the Python-Devmailing list

[8]ページ先頭

©2009-2025 Movatter.jp