Hi!
I just realized that <dict>.setdefau lt *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:
[color=blue][color=green][color=darkred]
>>> a = {}
>>> b = {}
>>> a.setdefault(1, b.setdefault(1, 1))[/color][/color][/color]
1
'1' didn't exist in a - so I expect 'b.setdefault(1 ,1)' to be
evaluated. Great.
[color=blue][color=green][color=darkred]
>>> a.setdefault(1, b.setdefault(2, 1))[/color][/color][/color]
1
'1' existed, so it's not necessary to evaluate 'b.setdefault(2 ,1)'.
But:
[color=blue][color=green][color=darkred]
>>> b[/color][/color][/color]
{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
I just realized that <dict>.setdefau lt *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:
[color=blue][color=green][color=darkred]
>>> a = {}
>>> b = {}
>>> a.setdefault(1, b.setdefault(1, 1))[/color][/color][/color]
1
'1' didn't exist in a - so I expect 'b.setdefault(1 ,1)' to be
evaluated. Great.
[color=blue][color=green][color=darkred]
>>> a.setdefault(1, b.setdefault(2, 1))[/color][/color][/color]
1
'1' existed, so it's not necessary to evaluate 'b.setdefault(2 ,1)'.
But:
[color=blue][color=green][color=darkred]
>>> b[/color][/color][/color]
{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
Comment