[Twisted-Python] help with Deferreds

How to rewrite this regular function with Deferred-style? def getCachedResult(cache, key): try: item = cache.open(key) except NotFound: return None try: if item.obsolete(): return None data = item.read() finally: item.release() result = renew(data) return result Conditions: 1. 'cache.open' and 'item.read' become deffered 2. 'item.obsolete()' and 'renew(data)' are not deferred

On Thu, Aug 26, 2010 at 11:47 AM, Sergey Magafurov <smagafurov@naumen.ru> wrote:
How to rewrite this regular function with Deferred-style?
Conditions: 1. 'cache.open' and 'item.read' become deffered 2. 'item.obsolete()' and 'renew(data)' are not deferred
I would probably write it something like this: def getCachedResult(cache, key): def _gotResult(item): try: if item.obsolete(): return None d = item.read() d.addCallback(lambda data: renew(data)) except: item.release() raise d.addBoth(lambda ign: item.release()) return d def _ebNotFound(f): f.trap(NotFound) return None return cache.open(key).addCallbacks(_gotResult, _ebNotFound) Note: code is untested -- mithrandi, i Ainil en-Balandor, a faer Ambar

I would probably write it something like this:
def getCachedResult(cache, key): def _gotResult(item): try: if item.obsolete(): return None d = item.read() d.addCallback(lambda data: renew(data)) except: item.release() raise d.addBoth(lambda ign: item.release()) return d
def _ebNotFound(f): f.trap(NotFound) return None
return cache.open(key).addCallbacks(_gotResult, _ebNotFound)
Note: code is untested
My variant is like yours. I ask this question because I am confusing with this ugly slice of code: try: ... except: item.release() raise Only inlineCallbacks helps me... Thanks.

On Thu, Aug 26, 2010 at 12:23 PM, Sergey Magafurov <smagafurov@naumen.ru> wrote:
I ask this question because I am confusing with this ugly slice of code:
try: ... except: item.release() raise
If you don't like that construct, perhaps this one is nicer: from twisted.internet.defer import maybeDeferred def getCachedResult(cache, key): def _readItem(item): if item.obsolete(): return None return item.read() def _gotResult(item): def _release(ign): item.release() return item d = maybeDeferred(_readItem, item) d.addBoth(_release) d.addCallback(renew) return d def _ebNotFound(f): f.trap(NotFound) return None return cache.open(key).addCallbacks(_gotResult, _ebNotFound) -- mithrandi, i Ainil en-Balandor, a faer Ambar

If you don't like that construct, perhaps this one is nicer:
from twisted.internet.defer import maybeDeferred
def getCachedResult(cache, key): def _readItem(item): if item.obsolete(): return None return item.read()
def _gotResult(item): def _release(ign): item.release() return item
d = maybeDeferred(_readItem, item) d.addBoth(_release) d.addCallback(renew) return d
def _ebNotFound(f): f.trap(NotFound) return None
return cache.open(key).addCallbacks(_gotResult, _ebNotFound Thanks, this is what I was looking for
participants (2)
-
Sergey Magafurov
-
Tristan Seligmann