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

Masklinn masklinn at masklinn.net
Fri May 20 19:51:30 CEST 2011


On 2011-05-20, at 18:31 , Ethan Furman wrote:
> Masklinn wrote:
>> I'm guessing the point is to be able to avoid the `if collection is None`
>> dance when the collection is not *supposed* to be modified: an immutable
>> collection would immediately raise on modification, acting as a
>> precondition/invariant and ensuring mutation is not introduced on the
>> original collection.
> 
> If the function can't proceed properly without an actual parameter, why supply a default?
It can, where did you get the idea that it could not? That's the point of the default parameter.

> But the original problem is that an empty list is used as the default because an actual list is expected.  I think the problem has been misunderstood -- it's not *if* the list gets modified, but *when* -- so you would have the same dance, only instead of None, your now saying
> 
> if default == empty():
>    default = []
> 
> So you haven't saved a thing, and still don't really get the purpose behind mutable defaults.
No, the point of empty() (or whatever it would be called) would very much be to forbid mutation of the default parameter. I used the word *if* because that is precisely what I meant: if the default parameter is modified, an error has been introduced into the function.

empty() is both an empty list (because the code iterates over a list for instance, or maps it, or what have you) and an assertion that this list is *not* to be modified.


More information about the Python-ideas mailing list