defaults for function arguments bound only once(??)

horos11 horos11 at gmail.com
Sun Oct 4 08:29:20 CEST 2009


All,

Another one, this time a bit shorter.

It looks like defaults for arguments are only bound once, and every
subsequent call reuses the first reference created. Hence the
following will print '[10,2]' instead of the expected '[1,2]'.

Now my question - exactly why is 'default_me()' only called once, on
the construction of the first object? And what's the best way to get
around this if you want to have a default for an argument which so
happens to be a reference or a new object?

---- code begins here ---

import copy
class A:

    def default_me():
        return [1,2]

    def __init__(self, _arg=default_me()):
        self.arg = _a


a = A()
a.arg[0] = 10
b = A()

print b.arg  # prints [10,2]



More information about the Python-list mailing list