Dumb python questions

Tim Peters tim.one at home.com
Wed Aug 15 23:45:11 EDT 2001


[Paul Rubin]
> ...
> Here's something I don't understand: why is it that the default
> value of a function arg is evaluated just once, instead of whenever
> the function is called?

Simply because that seemed most useful most often, and is most consistent
with the rest of the language:  default arguments are a kind of binding
performed at function definition time, and there are no instances of
"delayed assignment" anywhere in the language.  Note that "def" is an
executable statement in Python, not a declaration ("class" is also
executable, btw -- the only declaration in Python is the "global" stmt).

Note that this pattern is common:

import math

def angular(angle=math.pi):
    whatever

del math  # get this out of the module namespace

If the default arg were evaluated every time angular was called, the only
result of calling angular would be a runtime NameError (since "math" is
history by the time angular is called).

> The manual has a warning about that and examples of how to program
> around it, but it seems like poor design to need such a warning.

If it evaluated defaults every time the function got called, the manual
would have to give a warning about *that*, and examples of how to program
around it.

Since neither behavior is wholly compelling, you pick one and point out that
it isn't the other, or you drop the whole idea.

If we were afraid of operations someone might think work in a way other than
they actually do, we'd have to drop, oh, subscripting, addition and input
from Python too <wink>.  The question to me isn't whether a behavior may be
surprising, but whether it's easy to *remember* after you first learn it.
Everyone gets bit by the default argument rule once; few people seem to get
bit by it twice; and I *expect* they'd get bit more often if Guido had
picked the other rule.

adders = []
for i in range(10):
    def an_adder(a, b=i):
        return a+b
    adders.append(an_adder)

all-behaviors-are-exploitable-and-exploited-ly y'rs  - tim





More information about the Python-list mailing list