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

Masklinn masklinn at masklinn.net
Fri May 20 21:27:42 CEST 2011


On 2011-05-20, at 21:10 , Bruce Leban wrote:
> It seems to me that a better way of doing this is:
> 
>    def func(optional_list=[])
>        optional_list = freeze(optional_list)
> 
> That is, if I expect the list to be immutable when it's empty, why wouldn't
> I expect it to be immutable when it's not empty? The only case where the
> immutability of the empty list matters is if there's a bug that changes the
> list (or a called function changes its signature when that wasn't expected).
> Wouldn't it be worth protecting against that when the list isn't empty as
> well?

Absolutely, but the mutation of the default parameters seems to be the main
problem (historically): it's a memory leak, and it's a global data corruption,
where modifying a provided parameter is a local data corruption (unless the
object passed in is global of course).

Ideally, you could just add a decorator or an annotation doing that for you
without additional work and name mutation within the function.

> Anyway, in the case of a list I suspect that this is pretty close to what
> you want:
> 
>    def func(optional_list=[])
>        optional_list = tuple(optional_list)
But does not necessarily work depending on what callees demand (a callee
may be trying to concatenate that to a list of its own, and concatenating
lists and tuples does not work).

Plus, it does not help with dicts, which can expose the same issue.


More information about the Python-ideas mailing list