[Python-Dev] setdefault's second argument
David Goodger
goodger 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, then
delete them. This is because the "options" dict is passed on to
another function, where those entries are not welcome. The code above
is 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:
pass
It saves between one line and three lines of code per entry. But
since those entries are probably not so common, it would actually be
faster 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. Docutils
currently maintains compatibility with Python 2.1, so that's RIGHT
OUT!
> David, are you married to that bizarre use of setdefault <wink>?
No, not at all. In fact, I will vehemently deny that I ever wrote
such code, and will continue to do so until someone looks up its
history 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.asc
Type: application/pgp-signature
Size: 253 bytes
Desc: OpenPGP digital signature
Url : http://mail.python.org/pipermail/python-dev/attachments/20050830/8588c318/signature.pgp
More information about the Python-Dev
mailing list