[Twisted-Python] help with Deferreds

Terry Jones terry at jon.es
Thu Aug 26 04:44:52 MDT 2010


Hi Sergey

>      def checkObsolete(item):
>          if item.obsolete():
>              return None
>          else:
>              d = item.read()
>              d.addBoth(release, item)
>              d.addCallback(renew)
>              return d
>
>      d = cache.open(key)
>      d.addCallbacks(checkObsolete, notFound)
>      return d
>    

> Hi Terry
> If item.obsolete() raise exception item remain not released.
> Additional try ... except ... safe us but looks ugly

Yes, I was expecting you to wrap item.obsolete() and renew(data) in
try/except, as needed.  If you want a clean but slightly slower way to do
that, how about something like:


def getCachedResult(cache, key):

    def release(result, item):
        item.release()
        return result

    def renew(data):
        return renew(data)

    def notFound(fail):
        fail.trap(NotFound)

    def readItem(item):
        return item.read()

    def checkObsolete(item):
        d = defer.maybeDeferred(item.obsolete)
        d.addCallback(lambda _: readItem(item))
        d.addBoth(release, item)
        d.addCallback(renew)
        return d

    d = cache.open(key)
    d.addCallbacks(checkObsolete, notFound)
    return d




More information about the Twisted-Python mailing list