Discussion in 'Python' started by Tino Lange, Jul 31, 2003.

  1. Tino Lange

    Tino Lange Guest


    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!


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

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

    .... shows that it was executed!

    So it's not equivalent to:

    if 1not in a:

    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...


    Tino Lange, Jul 31, 2003
    1. Advertisements

  2. Tino Lange a écrit :
    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.
    Alexandre Fayolle, Jul 31, 2003
    1. Advertisements

  3. Tino Lange

    Tino Lange Guest

    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...


    Tino Lange, Jul 31, 2003
  4. Tino Lange

    Tino Lange Guest

    Of course. From the consistency point of view... perfectly right!
    (I thought that maybe because these are very special low-level methods
    for built-in types, it might be different....)
    or the C-like style:

    Tino Lange, Jul 31, 2003
  5. 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.
    Erik Max Francis, Jul 31, 2003
  6. Quoth Tino Lange:
    Be careful doing that -- it relies on all possible values for a[1]
    being true. Consider:
    {4: 1}
    Steven Taschuk, Aug 1, 2003
    1. 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 (here). After that, you can post your question and our members will help you out.