expression form of one-to-many dict?

Fredrik Lundh fredrik at pythonware.com
Sun Dec 19 15:29:27 EST 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
anything:

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

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

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

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

</F> 






More information about the Python-list mailing list