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

Jack Diederich jackdied at gmail.com
Fri May 20 06:46:14 CEST 2011


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.

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.

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:

class empty():
    def _bad_user(self, *args):
      raise ValueError("empty objects are empty")
    append = pop = __getitem__ = add = setdeafult = __ior__ = __iand__
= _bad_user
    def _empty(self):
      return []
    items = keys = values = get = _empty

return nothing when asked for something and raise a ValueError when
any attempt is made to add/remove items.

-Jack



More information about the Python-ideas mailing list