[Python-ideas] function defaults and an empty() builtin

Masklinn masklinn at masklinn.net
Fri May 20 20:15:18 CEST 2011


On 2011-05-20, at 17:03 , Nick Coghlan wrote:
> I share Steve's puzzlement as the intended use case.
> 
> To get value from the magic empty immutable list, you will have to
> explicitly test that calling your function with the default value does
> the right thing.
Why is that? The value of the empty immutable list (there's nothing magic
to it) would be an eternal assertion that an incorrect behavior (trying
to mutate the default parameter) can not be introduced in the function.

It is no different than adding `assert` calls in the code.

> But if you're writing an explicit test, having that test call the
> function *twice* to confirm correct use of the 'is None' idiom will
> work just as well.
But that's the point: do you *always* use the `is None` idiom? And do
you really love it? When you know the function body you just wrote
does not perform any modification to the collection?

There are 17 functions or methods with list default parameters and
133 with dict default parameters in the Python standard library.

Surely some of them legitimately make use of a mutable default
parameter as some kind of process-wide cache or accumulator, but
I would doubt the majority does (why would SMTP.sendmail need to
accumulate data in its mail_options parameter across runs?)

Do you know for sure that no mutation of these 150+ parameters will
ever be introduced, that all of these functions and methods are
sufficiently tested, called often enough that the introduction of
a mutation of the default parameter in themselves or one of their
callees would *never* be able to pass muster?



More information about the Python-ideas mailing list