Bizarre behavior with mutable default arguments
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Dec 29 19:43:55 EST 2007
On Sat, 29 Dec 2007 09:50:53 -0800, bukzor wrote:
> I've found some bizzare behavior when using mutable values (lists,
> dicts, etc) as the default argument of a function.
This FAQ is so Frequently Asked that I sometimes wonder if Python should,
by default, print a warning when it compiles a function with a list or
dict as as default value.
There's precedence for such a thing: the sum() built-in (un)helpfully
raises an exception if you try to use it on strings.
I say unhelpfully because the one time I wanted to use sum() on strings
was specifically to demonstrate the difference between O(n**2) behaviour
and O(n). I was quite put out that Python, which normally allows you to
shoot yourself in the foot if you insist, was so unnecessarily protective
in this case. Give me a warning, if you wish, but don't stop me.
--
Steven
More information about the Python-list
mailing list