default method parameter behavior
Primoz Skale
primoz.skale.lists at gmail.com
Wed Apr 2 16:55:07 EDT 2008
<jianbing.chen at gmail.com> wrote in message
news:879d72da-825f-4b2b-8244-87367647fb6e at f63g2000hsf.googlegroups.com...
>I ran into a similar situation like the following (ipython session).
> Can anyone please explain why the behavior?
> Thanks in advance.
>
> In [11]: def foo(b=[]):
> ....: b.append(3)
> ....: return b
> ....:
>
> In [12]: foo()
> Out[12]: [3]
>
> In [13]: foo()
> Out[13]: [3, 3]
>
> In [14]: foo([])
> Out[14]: [3]
>
> In [15]: foo([])
> Out[15]: [3]
I think it has something to do with foo.func_defaults thing :) If parameter
that is assigned a default value is mutable then foo.func_defaults is
changed everytime there is no parameter passed to the function.
For example:
>>> def f(b=[]):
b.append(3)
return b
>>> f.func_defaults #default is [], because function was not yet called
([],)
>>> f() #no args
[3]
>>> f.func_defaults #default is now b=[3], because b is mutable object
([3],)
>>> f([]) #empty; default still == [3]
[3]
>>> f.func_defaults #as we can see here
([3],)
>>> f() #again no args; default is changed to [3,3]
[3, 3]
>>> f.func_defaults
([3, 3],)
>>> f([]) #no args
[3]
>>> f.func_defaults
([3, 3],)
As *I* understand it, it goes something like this. Because mutable objects
change globaly if not passed correctly, and because [] is mutable, python
creates a *def global* object, which is only seen by function that created
it, with a name b to which it assigns a default value of []. But when this
default [] is changed in function, it becomes [3], and so on.....
Correct me if I am wrong...
P.
More information about the Python-list
mailing list