Beware of side effects on default arguments

Check out this quick interactive session:

Python 2.7.12 (default, Jul  1 2016, 15:12:24) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(y, x={}):
...   print x
...   if y:
...     x['y'] = True
... 
>>> f(False)
{}
>>> f(False, {'x': True})
{'x': True}
>>> f(True, {'x': True})
{'x': True}
>>> f(False)
{}
>>> f(True)
{}
>>> f(False)
{'y': True}
>>> f(True, {'x': True})
{'x': True}
>>> f(False)
{'y': True}

What’s wrong with this picture? Notice that when I call f(True) we assign something to the default argument x. When we call f again, it replaces the default x = {} with the previous value of x!

I suppose the moral of the story here is that in order to avoid side effects, you should not mess with arguments you’re passing in, even if they’re just the default arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *