[Tutor] Surprising behaviour of optional argument

Jose Amoreira ljmamoreira at gmail.com
Thu Jul 17 19:26:43 CEST 2014


Hello
I stumbled on something I found surprising. I'm using standard python 
(cpython, I guess) 2.7 on openSuse 13.1.

Consider the function

In [2]: def f(x,y=[]):
    ...:     print y
    ...:     y.append(x)
    ...:     return x

This is the output of repeated calls to this function:

In [3]: f(1)
[]
Out[3]: 1
In [4]: f(2)
[1]
Out[4]: 2
In [5]: f(3)
[1, 2]
Out[5]: 3

So, the function seems to keep the value of the optional argument y over 
repeated calls. I was expecting that the optional argument, if not set 
explicitly in the calling command, would always assume the default value 
(the empty list), at every call.

I guess it has something to do with the mutability of the optional 
argument (in this case, a list), because it works as I expect if the 
optional argument is an int, for instance:

In [8]: def g(x,y=0):
    ...:     print y
    ...:     y += x
    ...:     return x
    ...:

In [9]: g(1)
0
Out[9]: 1
In [10]: g(2)
0
Out[10]: 2

(No memory of previous calls to the function.)
Is there a rationale for this behavior?
Thanks for any help,
Ze


More information about the Tutor mailing list