<dict>.setdefault()


T

Tino Lange

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:
1

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

'1' existed, so it's not necessary to evaluate 'b.setdefault(2,1)'.
But:
{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
 
Ad

Advertisements

A

Alexandre Fayolle

Tino Lange a écrit :
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.

Since setdefault is a method, this is coherent with Python's standard
behaviour: method and function arguments are always evaluated before the
method is called.
 
T

Tino Lange

method and function arguments are always evaluated before the
method is called.

Yep. You're right. Of course it's like that.
Anyway - that's not what I expected in the first thought.

It shows that less code is not always the best code...

Thanks!

Tino
 
E

Erik Max Francis

Tino said:
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!

Because Python doesn't have macros or special forms that look like
functions. If you see something that looks like a function, it
evaluates all arguments before it calls the function. Always. Changing
this would cause confusion, not resolve it.
 
Ad

Advertisements

S

Steven Taschuk

Quoth Tino Lange:
On 31 Jul 2003 18:01:51 +0100, (e-mail address removed) (John J. Lee) wrote: [...]
Don't, then. :) Use key in dict, or dict.has_key(key).

or the C-like style:
a[3] = a.get(1) or b.setdefault(4,1)

Be careful doing that -- it relies on all possible values for a[1]
being true. Consider:
>>> a = {1: 0}
>>> b = {}
>>> a[3] = a.get(1) or b.setdefault(4, 1)
>>> a {1: 0, 3: 1}
>>> b
{4: 1}
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top