Should Python raise a warning for mutable default arguments?

Carl Banks pavlovevidence at gmail.com
Sat Aug 23 10:40:21 EDT 2008


On Aug 23, 4:09 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 22 Aug 2008 20:37:09 -0700, Carl Banks wrote:
> > 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.  
>
> There's nothing questionable about using a mutable default argument, so
> long as you know what behaviour to expect. I too use that behaviour, I
> like that behaviour, and I'm tired of people who want it "fixed".
>
> Nevertheless, it is surprising to many people. My aim is to make it a
> little less surprising.
>
> > Python shouldn't raise a warning just
> > because something *might* be due to a misunderstanding.
>
> That's one opinion.

1. When you print spurious warnings, the overall effectiveness of the
warning system is diminished.  People start to ignore them, either by
disabling them or by mentally tuning out.  This in turn makes people
less likely to notice if a real warning is printed.

When you print a warning, you better be %99.9 sure that it's something
worth warning about, otherwise you are doing more harm than good.

(Story time: I once worked on a system that displayed warnings to jet
fighter pilots.  Our requirements were not to show the pilot a warning
unless the airplane actually tries something and fails, even if the
computer is absolutely sure that it would fail.  Ex: if computer knows
for sure the engine can't produce more than (say) 50% rated thrust,
the pilot does not get a warning unless he actually requests more than
50% thrust.  The reason is for this, according to the senior engineers
on the team, was that pilots would start to ignore the warning lights
REALLY FAST.)


2. It's rude to be presumptuous, which is what the compiler would be
if it printed this warning.


Carl Banks



More information about the Python-list mailing list