[Python-ideas] fixing mutable default argument values

Josiah Carlson jcarlson at uci.edu
Thu Jan 18 17:47:14 CET 2007


Chris Rebert <cvrebert at gmail.com> wrote:
> 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()
> [666]
>  >>> popo()
> [666, 666]
>  >>> popo()
> [666, 666, 666]
[snip]
> Comments?

As provided by Calvin Spealman, the above can be fixed with:

    def popo(x=None):
        x = x if x is not None else []
        x.append(666)
        print x

I would also mention that forcing users to learn about mutable arguments
and procedural programming is not a bad thing.  Learning the "gotcha"
of mutable default arguments is a very useful lesson, and to remove that
lesson, I believe, wouldn't necessarily help new users to Python, or new
programmers in general.

 - Josiah




More information about the Python-ideas mailing list