[Python-ideas] function defaults and an empty() builtin
Masklinn
masklinn at masklinn.net
Fri May 20 21:10:25 CEST 2011
On 2011-05-20, at 21:12 , Ethan Furman wrote:
>
> 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?
It will not until one day func() is called without an actual list, and then you get a clear and immediate error instead of silent data corruption, or a memory leak, which are generally the result of an improperly mutated default argument collection and much harder to spot.
As I wrote in part of the message you quoted (but ignored), empty() acts as an assertion. The assertion is that the default parameter will never be modified, and if the assertion fails, an error is generated.
That's it. That's a pretty common bug in Python, and it solves it. No more, and no less.
More information about the Python-ideas
mailing list