Should Python raise a warning for mutable default arguments?
castironpi at gmail.com
Fri Aug 22 18:53:05 CEST 2008
On Aug 22, 9:42 am, Steven D'Aprano <st... at REMOVE-THIS-
> 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
> What do people think?
I like the idea of calling it to your attention. +1.
If a warning, you should be able to silence it with an annotation,
decorator, or a module-level flag.
Or perhaps, require it be declared explicit, and make it an error.
def test(x, a=defmut()):
Python raises an actual error unless default arguments are known
immutable or instances of 'defmut'.
More information about the Python-list