Death to tuples!

Mike Meyer mwm at mired.org
Thu Dec 1 18:40:18 EST 2005


Antoon Pardon <apardon at forel.vub.ac.be> writes:
> On 2005-12-01, Mike Meyer <mwm at mired.org> wrote:
>> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>>> I know what happens, I would like to know, why they made this choice.
>>> One could argue that the expression for the default argument belongs
>>> to the code for the function and thus should be executed at call time.
>>> Not at definion time. Just as other expressions in the function are
>>> not evaluated at definition time.
>>
>> The idiom to get a default argument evaluated at call time with the
>> current behavior is:
>>
>>         def f(arg = None):
>>             if arg is None:
>>                arg = BuildArg()
>>
>> What's the idiom to get a default argument evaluated at definition
>> time if it were as you suggested?
>
> Well there are two possibilities I can think of:
>
> 1)
>   arg_default = ...
>   def f(arg = arg_default):
>      ...

Yuch. Mostly because it doesn't work:

arg_default = ...
def f(arg = arg_default):
...

arg_default = ...
def g(arg = arg_default):

That one looks like an accident waiting to happen.

> 2)
>   def f(arg = None):
>     if arg is None:
>       arg = default.

Um, that's just rewriting the first one in an uglier fashion, except
you omitted setting the default value before the function.

This may not have been the reason it was done in the first place, but
this loss of functionality would seem to justify the current behavior.

And, just for fun:

def setdefaults(**defaults):
    def maker(func):
        def called(*args, **kwds):
            defaults.update(kwds)
            func(*args, **defaults)
        return called
    return maker

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list