Should Python raise a warning for mutable default arguments?

Peter Otten __peter__ at web.de
Fri Aug 22 11:32:42 EDT 2008


Christian Heimes wrote:

> Steven D'Aprano wrote:
>> 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?

-0 from me. I'd rather feature it more prominently in the tutorial, a
section "The five most common pitfalls" or something like that.

> I don't see a chance for your proposal. How are you going to detect
> mutable objects? Custom types can be mutable as well as immutable.

A check at compilation time for list literals would catch 90 % of the cases.
The warning would be targeted at newbies after all. It might still be a
source of confusion when they try to import someone else's code that uses
mutable defaults intentionally.

Peter



More information about the Python-list mailing list