Default Parameters to function!

Tim Peters tim_one at
Thu Mar 16 02:07:57 CET 2000

[Timothy Docker, arguing for default args to get evaluated at call-time
 rather than at definition-time]
> ...
> Is there any reason why this shouldn't be considered for python
> 3000?

No reason not to consider it.

> Just about everyone hits this sooner or later,

Yes, most Python programmers hit it exactly twice <0.9 wink> before their
first (& last) "aha! now I get it -- that's simple!" experience.

> suggesting that that the current behaviour is not the ideal one.

It certainly is not.  OTOH, do we have evidence that the other behavior is?
The notion that there is *an* "ideal behavior" here seems exceedingly
dubious to me.  If after:

import random
def shuffle(seq, random=random.random):
    """Permute seq randomly in place.

    Optional arg random is a no-argument function returning a
    random real in [0, 1).  By default, random.random is used.
    You may wish to supply a more powerful generator for high
    resolution experiments.

    # etc, w/ code invoking random()

del random  # so "import *" doesn't pollute the caller's namespace

an attempt to call shuffle(somelist) blew up with a NameError on random
while evaluating the default arg, I'd be pissed off.

The fact is the implementation can't possibly guess what the user intended
by staring at the code, so both behaviors suck (albeit for different reasons
in different situations).  That makes the default-argument feature-- no
matter how implemented --un-Pythonic on the face of it!  OTOH, it's too
useful to give up.

I don't see a good reason to change it, since either way will be surprising;
you just have to get used to it.  The current way wins big on simplicity of
implementation (making it easy to predict what will happen in all cases).

    y'rs  - tim

More information about the Python-list mailing list