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

Steven D'Aprano steve at pearwood.info
Fri May 20 07:57:04 CEST 2011


On Fri, 20 May 2011 02:46:14 pm Jack Diederich wrote:
> During a code review I got asked a question about a "pythonic" idiom
> I've been asked about before.  The code was like this:
>
> def func(optional=None):
>   if optional is None:
>     optional = []
>
> The question was why the optional value wasn't set to an empty list
> in the first place.  The answer is that Really Bad Things can happen
> if someone actually goes and manipulates that empty list because all
> future callers will see the modified version.

Assuming that this behaviour is not intended. However, I agree that, in 
general, the behaviour of mutable defaults in Python is a Gotcha.


> I don't think this defensive programming practice is yet passe - I
> can think of lots of unit tests that wouldn't trigger bad behavior. 
> You would have to intentionally provoke it by adding some unit tests
> to be sure.

Er, yes... how is that different from any other behaviour, good or bad? 
You have to write the unit tests to test the behaviour you want to test 
for, or else it won't be tested.


> What would make my life a little easier is a builtin container named
> "empty()" that emulates all builtin containers and raises an
> exception for any add/subtract manipulations.  Something like:

I don't think that this idea will actually be as useful as you think it 
will, but in any case, why does it need to be a built-in?

def func(optional=empty()):
    ...

works just as well whether empty is built-in or not.

But as I said, I don't think this will fly. What's the point? If you 
don't pass an argument for optional, and get a magic empty list, your 
function will raise an exception as soon as it tries to do something 
with the list. To my mind, that makes it rather useless. If you want 
the function to raise an exception if the default value is used, surely 
it's better to just make the argument non-optional.

But perhaps I've misunderstood something.




-- 
Steven D'Aprano



More information about the Python-ideas mailing list