Should Python raise a warning for mutable default arguments?

Carl Banks pavlovevidence at gmail.com
Fri Aug 22 23:37:09 EDT 2008


On Aug 22, 10:42 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> Sometimes it seems that barely a day goes by without some newbie, or not-
> so-newbie, getting confused by the behaviour of functions with mutable
> default arguments. No sooner does one thread finally, and painfully, fade
> away than another one starts up.
>
> I suggest that Python should raise warnings.RuntimeWarning (or similar?)
> when a function is defined with a default argument consisting of a list,
> dict or set. (This is not meant as an exhaustive list of all possible
> mutable types, but as the most common ones that I expect will trip up
> newbies.) The warning should refer to the relevant FAQ or section in the
> docs.
>
> What do people think?

-1

There's nothing questionable about using a mutable default argument,
as long as you don't mutate it.  Python shouldn't raise a warning just
because something *might* be due to a misunderstanding.

I usefully use mutable default arguments all the time.  Most commonly
in situations like this:

def f(data,substitutions = {}):
    ...
    name = data['name']
    obj.name = substitutions.get(name,name)
    ...


-0 on adding a warning that's disbaled by default.


Carl Banks



More information about the Python-list mailing list