Keyword arguments - strange behaviour?
Duncan Booth
duncan.booth at invalid.invalid
Tue Dec 21 05:41:36 EST 2004
wrote:
> Can anyone explain the behaviour of python when running this script?
>
>>>> def method(n, bits=[]):
> ... bits.append(n)
> ... print bits
> ...
>>>> method(1)
> [1]
>>>> method(2)
> [1, 2]
>
> It's the same in python 1.5, 2.3 and 2.4 so it's not a bug. But I
> expected the variable "bits" to be re-initialised to an empty list as
> each method was called. Whenever I explain optional keyword arguments
> to someone I have usually (wrongly as it turns out) said it is
> equivalent to:
<snipped erroneous comparison>
No, it is closer to:
# Assume you have done this earlier:
import new
def _realmethod(n, bits):
bits.append(n)
print bits
# The def is roughly equivalent to this:
_defaultArgs = ([], )
method = new.function(_realmethod.func_code, globals(), 'method',
_defaultArgs)
Each time you re-execute the def you get a new set of default arguments
evaluated, but the result of the evaluation is simply a value passed in to
the function constructor.
The code object is compiled earlier then def creates a new function object
from the code object, the global dictionary, the function name, and the
default arguments (and any closure as well, but its a bit harder to
illustrate that this way).
More information about the Python-list
mailing list