Should Python raise a warning for mutable default arguments?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Aug 22 20:08:14 EDT 2008


On Fri, 22 Aug 2008 17:09:34 +0200, 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?
> 
> 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.

It is not meant to catch all conceivable mutable types, just the three 
most likely to surprise newbies.

The analogy is with the sum() built-in, which raises an exception if you 
use it to add strings. (Personally, I think it should raise a warning, 
not an exception, and allow people to write slow code if they want.) 
Python doesn't attempt to detect every single type that leads to O(n**2) 
behaviour in sum(), just the one most likely to trip up newbies.

But if people decide that it is important to warn on any conceivable 
mutable type, the easy way is to approach the question from the other 
direction. If the default value *isn't* a string, int, float, None or 
frozenset, assume it's mutable.

Personally I don't think it's important to catch every case. After all, 
it's just a warning, not an error.



-- 
Steven



More information about the Python-list mailing list