Curious function argument

ast nomail at invalid.com
Wed Nov 12 08:07:14 EST 2014


Hello

I saw in a code from a previous message in this forum
a curious function argument.

def test(x=[0]):
   print(x[0])   ## Poor man's object
   x[0] += 1

>>> test()
0
>>> test()
1
>>> test()
2
>>> 

I understand that the author wants to implement a global
variable x . It would be better to write 'global x' inside the
function.

At first test() function call, it prints 0, that's OK.
But at the second call, since we dont pass any argument to test(),
x should be equal to its default value [0] (a single item list). But
it seems that Python keeps the original object whose content has
been changed to 1.

Is it a usual way to implement a global variable ?

thx








More information about the Python-list mailing list