[Python-ideas] function defaults and an empty() builtin
Ethan Furman
ethan at stoneleaf.us
Fri May 20 21:12:45 CEST 2011
Masklinn wrote:
> 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?
In this scenario:
def func(mylist=empty()):
do_some_stuff_with_mylist
mylist is the empty() object, you *know* func() does not modify mylist,
you are wrong (heh) and it does... but your program always calls func()
with an actual list -- how is empty() going to save you then?
Hint: it won't.
And if you're thinking a unittest would catch that -- yes it would, but
it would also catch it without empty() (make a copy first, call the
func(), compare afterwards -- different? Mutation!)
~Ethan~
More information about the Python-ideas
mailing list