Santiago Palladino

Santiago Palladino

Careful when using mutable types as default arguments in Python

2 min
Aug 18 2010
2 min
Aug 18 2010

As an intermezzo in the blog posts regarding my thesis, I'd like to point out an unexpected (or at least, unexpected for me) behaviour in Python's way of constructing default arguments.

Suppose we have the following python class MyClass, with an initializer with a default list parameter:

class MyClass:
def __init__(self, list=[]):
self.list = list

What happens if we initialize two different instances of this class, and modify one of them by adding an item to its underlying list?

foo = MyClass()
bar = MyClass()


print 'foo.list: ', foo.list
print 'bar.list: ', bar.list

Well, the output is the following:

foo.list: [10]
bar.list: [10]

What happened here? The default value for the list parameter in the class initializer is evaluated only once, when the class is loaded, and therefore only one instance of list is created. In other words, all instances of MyClass using the default value for list will share the same list instance, so when one of them is modified, all of them are.