Mutable default arguments

Python primitive types are immutable. Objects though, including lists and dictionaries are mutable.
This can cause a problem when they’re used as the default argument to a function.

Consider the following code:

def append(item, dest=[]):
    return dest

def main():
    order1 = append('spam')
    print order1
    order2 = append('eggs')
    print order2

if __name__ == '__main__':

You would think that this code would print:


In fact it prints:

['spam', 'eggs']

This is because the default argument, rather than being evaluated every time the function is called, is evaluated just once when the function definition is compiled.

The way to get the expected behaviour is to rewrite the function as follows:

def append(item, dest=None):
    if dest is None:
        dest = []
    return dest