<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >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. -- http://mail.python.org/mailman/listinfo/python-list