Skip to content

Instantly share code, notes, and snippets.

@matze
Last active December 14, 2016 21:55
Show Gist options
  • Save matze/5325713 to your computer and use it in GitHub Desktop.
Save matze/5325713 to your computer and use it in GitHub Desktop.
promise decorator to resolve future arguments
from concurrent.futures import Future, ThreadPoolExecutor
class promise(object):
executor = ThreadPoolExecutor(max_workers=100)
def __init__(self, func):
self.func = func
def resolve(self, *args, **kwargs):
resolved_args = []
resolved_kwargs = {}
for i, arg in enumerate(args):
if isinstance(arg, Future):
resolved_args.append(arg.result())
else:
resolved_args.append(arg)
for kw, arg in kwargs.items():
if isinstance(arg, Future):
resolved_kwargs[kw] = arg.result()
else:
resolved_kwargs[kw] = arg
return self.func(*resolved_args, **resolved_kwargs)
def __call__(self, *args, **kwargs):
return self.executor.submit(self.resolve, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment