defaults for function arguments bound only once(??)

Simon Forman sajmikins at gmail.com
Sun Oct 4 19:15:37 CEST 2009


On Sun, Oct 4, 2009 at 2:29 AM, horos11 <horos11 at gmail.com> wrote:
> 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?

This is a FAQ: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects

>
> ---- 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]

Your code is weird:  you import copy module but don't use it; you
define default_me() as a "sort of" static method
(http://docs.python.org/library/functions.html#staticmethod) but then
only use it to generate a default argument that has nothing to do with
the class you just defined; and in __init__() you use "_a" which isn't
defined anywhere in this code snippet.

What are you actually trying to accomplish?



More information about the Python-list mailing list