[Tutor] default argument frustration

Alan Gauld alan.gauld at freenet.co.uk
Sun Feb 13 10:45:49 CET 2005


> I've combined a few email's worth of quoting as no previous post had
> all the elements I wanted to refer to.

>  > interface. The function should return the same result each time
>  > you call it with the same input. The only way to achieve that
>  > is to have the default calculated once.

I feel the need to clarify this statement somewhat! :-)

Imagine what would happen if you calculated the default each time
you ran the program and the def looked like:

def f(x,y=g()):
   # etc...

Everytime you called f(42) you would also call g() which could return
a completely different value, thus f(42) behaviour would be very
inconsistent and almost unpredictable.

However if g() is only evaluated once and that value used as the
default then f(42) becomes predictable again.

If you want the behaviour whereby g() gets called each time then
that is easily restored by making the function object g be the
default and then within the function definition calling it:

def g(): # whatever
def f(x,y=g):
   val = g()
   # etc...

Hmm, I'm not sure this is actually explaining what I'm trying to
say...
Basically, I think the current behaviour is good because it gives me
a wider set of options than the alternative mechanism.

Alan G.



More information about the Tutor mailing list