expression form of one-to-many dict?

Fredrik Lundh fredrik at
Sun Dec 19 21:29:27 CET 2004

Mike Meyer wrote:

> Personally, I'd love a language feature that let you create a function
> that didn't evaluate arguments until they were actually used - lazy
> evaluation. That lets you write the C ?: operator as a function, for
> a start.
> Hmmm. No, iterators can't be used to fake it. Oh well.

if you can get some collaboration from the function itself, you can fake

def foo_default():
     while 1:
          print "MAKE A FOO"
          yield "foo"
foo_default = foo_default()

class mydict(dict):
     def setdefault(self, key, default=None):
               return self[key]
          except KeyError:
               if hasattr(default, "next"):
                    default =
               self[key] = default
               return default

d = mydict()
d["spam"] = "bacon"

print d.setdefault("spam", foo_default)
print d.setdefault("egg", foo_default)


More information about the Python-list mailing list