[Python-Dev] dict "setdefault". Feaure request or bugfix?

Jesus Cea Avion jcea@argo.es
Tue, 11 Feb 2003 13:23:35 +0100


<https://sourceforge.net/tracker/index.php?func=detail&aid=684542&group_id=5470&atid=355470>

Reading "python cookbook" I reach a very intelligent
dictionary construction: to use dictionary "setdefault"
to avoid a "get" or a "try...except".

Nevertheless current "setdefault" behaviour is
questionable, since it evaluates the default value when
it is not necessary. In my mind, "setdefault" should
evaluate the default value when it need to use it, not
ALWAYS. Example:

>>> a={}
>>> def b() :
... print "hi!"
... return 1
...
>>> a.setdefault("hola","hello")
hello
>>> print a
{'hola': 'hello'}
>>> a.setdefault("hola",b())
hi!
'hello'

In the example, the "setdefault" evaluation is not
necessary since 'a["hola"]' already exists. But the default
function is called, although its return value will be
ignored.

This behaviour is not intuitive and I think it should
be changed or, at least, documented. The change would
be very welcome when the "setdefault" default code is
expensive, like my application. In any case, the change
would be ALWAYS more efficient, even in the tipical
"[]" case.

Perhaps a "form __future__ import setdefaultNG" would
be necessary to help to update legacy code?

Opinions?.

-- 
Jesus Cea Avion                         _/_/      _/_/_/        _/_/_/
jcea@argo.es http://www.argo.es/~jcea/ _/_/    _/_/  _/_/    _/_/  _/_/
                                      _/_/    _/_/          _/_/_/_/_/
PGP Key Available at KeyServ   _/_/  _/_/    _/_/          _/_/  _/_/
"Things are not so easy"      _/_/  _/_/    _/_/  _/_/    _/_/  _/_/
"My name is Dump, Core Dump"   _/_/_/        _/_/_/      _/_/  _/_/
"El amor es poner tu felicidad en la felicidad de otro" - Leibniz