[Python-ideas] fixing mutable default argument values

Chris Rebert cvrebert at gmail.com
Mon Jan 15 02:19:09 CET 2007

If A.M. Kuchling's list of Python Warts is any indication, Python has 
removed many of the warts it once had. However, the behavior of mutable 
default argument values is still a frequent stumbling-block for newbies. 
It is also present on at least 3 different lists of Python's 
deficiencies ([0][1][2]).

Example of current, unintuitive behavior (snipped from [0]):
 >>> def popo(x=[]):
...     x.append(666)
...     print x
 >>> popo()
 >>> popo()
[666, 666]
 >>> popo()
[666, 666, 666]

Whereas a newbie with experience with immutable default argument values 
would, by analogy, expect:
 >>> popo()
 >>> popo()
 >>> popo()

In scanning [0], [1], [2], and other similar lists, I have only found 
one mediocre use-case for this behavior: Using the default argument 
value to retain state between calls. However, as [2] comments, this 
purpose is much better served by decorators, classes, or (though less 
preferred) global variables. Other uses are alluded to be equally 
esoteric and unpythonic.

To work around this behavior, the following idiom is used:
def popo(x=None):
     if x is None:
         x = []
     print x

However, why should the programmer have to write this extra boilerplate 
code when the current, unusual behavior is only relied on by 1% of 
Python code?

Therefore, I propose that default arguments be handled as follows in Py3K:
1. The initial default value is evaluated at definition-time (as in the 
current behavior).
2. That in a function call where the caller has not specified a value 
for an optional argument, Python calls 
copy.deepcopy(initial_default_value), and fills in the optional argument 
with the resulting value.

This is fully backwards-compatible with the aforementioned workaround, 
and removes the need for the it, allowing one to write the first, 
simpler definition of popo().


- Chris Rebert

[0] 10 Python pitfalls (http://zephyrfalcon.org/labs/python_pitfalls.html)
[1] Python Gotchas 
[2] When Pythons Attack 

More information about the Python-ideas mailing list