Mutable default values can change

When you use a mutable object (such as a list, dictionary, or class instance) as a default and change the object inside the function, then the next time you call the function, the function uses the changed object. For example, the following function creates a list that accumulates the arguments passed to it.

>>> def f(q, mylist=[]): ... mylist.append(q)

... return mylist

>>> print f('b') ['a', 'b'] >>> print f('c') ['a', 'b', 'c']

Here's what's going on:

1. When the function is defined, it creates an empty list object named mylist.

2. Inside the function, the append() method adds an item to the list.

The append() method changes the contents of the list in place— that is, mylist still refers to the same object after being changed.

3. When the function is called again, it grabs the same list from the same place and uses the new contents.

Was this article helpful?

0 0

Post a comment