[Python-bugs-list] [ python-Feature Requests-684542 ] dict setdefault lazy evaluation

SourceForge.net noreply@sourceforge.net
Thu, 20 Mar 2003 04:59:06 -0800


Feature Requests item #684542, was opened at 2003-02-11 13:26
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=684542&group_id=5470

Category: Python Interpreter Core
Group: None
>Status: Closed
Resolution: Invalid
Priority: 5
Submitted By: Jesús Cea Avión (jcea)
Assigned to: Nobody/Anonymous (nobody)
Summary: dict setdefault lazy evaluation

Initial Comment:
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"]' 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?

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=684542&group_id=5470