Skip to content

Instantly share code, notes, and snippets.

@schlamar
Last active December 19, 2015 13:59
Show Gist options
  • Save schlamar/5965809 to your computer and use it in GitHub Desktop.
Save schlamar/5965809 to your computer and use it in GitHub Desktop.
Some helpers for PEP 3156 Futures.
def link(f, other):
'''Resolve other with the current Future.'''
def on_done(f):
e = f.exception()
if e:
other.set_exception(e)
else:
other.set_result(f.result())
f.add_done_callback(on_done)
def cancel_on_cond(f, cond, callback):
''' Cancel the future if condition is fulfilled else it
processes the callback.
'''
ret_f = Future()
def on_done(f):
# sane exception handling ?!
r = f.result()
if cond(r):
ret_f.cancel()
else:
inner_f = callback(r)
link(inner_f, ret_f)
f.add_done_callback(on_done)
return ret_f
def next(f, callback):
'''Filter the result of the Future and pass it to
the callback.
'''
ret_f = Future()
def on_done(f):
r = f.result()
inner_f = callback(r)
link(inner_f, ret_f)
return ret_f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment