Curious function argument

ast nomail at
Wed Nov 12 14:07:14 CET 2014


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()
>>> test()
>>> test()

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

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 ?


More information about the Python-list mailing list