<dict>.setdefault()

Tino Lange tl_news at nexgo.de
Thu Jul 31 12:35:51 EDT 2003


Hi!

I just realized that <dict>.setdefault *always* executes the second
argument - even if it's not necessary, because the requested item in
the first argument exists.

This is not what I expected - why evaluate the second argument if it's
not needed? Also this can lead to side-effects!

Example:

>>> a = {}
>>> b = {}
>>> a.setdefault(1,b.setdefault(1,1))
1

'1' didn't exist in a - so I expect 'b.setdefault(1,1)' to be
evaluated. Great.

>>> a.setdefault(1,b.setdefault(2,1))
1

'1' existed, so it's not necessary to evaluate 'b.setdefault(2,1)'.
But:

>>> b
{2: 1, 1: 1}

... shows that it was executed!

So it's not equivalent to:

if 1not in a:
   b.setdefault(2,1)

Is this really  by design? If there's a complicated, expensive to
calculate/build 2nd argument (maybe a function call) then it's also
quite ineffective to evaluate it just to throw away...

Thanks!

Tino





More information about the Python-list mailing list