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

Ethan Furman ethan at stoneleaf.us
Fri May 20 18:31:04 CEST 2011


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?  Make it required, and then the function will blow up 
when it's called without one.

I suppose there could be a case where one is going to iterate through a 
collection, and useful work may still happen if said collection is 
empty, and one is feeling too lazy to create an empty one on the spot 
where the function is called and so relies an the immutable empty 
default... but if one knows all that one should be able to not call any 
mutating methods.

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.

~Ethan~



More information about the Python-ideas mailing list