Mel Wilson mwilson at the-wire.com
Thu Jul 31 22:11:49 CEST 2003

In article <kmgiivclivi0vhbgr6adel4dafflq6i6ir at 4ax.com>,
Tino Lange <tl_news at nexgo.de> wrote:
>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.
>[ ... ]
>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...

   Like they say, it's the way all functions, like
setdefault, work.  Arguments have to be evaluated before the
function is called.  Maybe you want

            some_var = some_dict[key]
        except KeyError:
            some_var = some_dict[key] = default_expression_value

in code where `default_expression_value` isn't ready to
hand.  Lazy evaluation is easy, as long as you don't mind
using statements.

        Regards.        Mel.

More information about the Python-list mailing list