Skip to content

Instantly share code, notes, and snippets.

@victor-shepardson
Last active January 20, 2020 05:01
Show Gist options
  • Save victor-shepardson/a167f7a52e1d0154a82568be62aa0789 to your computer and use it in GitHub Desktop.
Save victor-shepardson/a167f7a52e1d0154a82568be62aa0789 to your computer and use it in GitHub Desktop.
write a function once as a coroutine and easily get blocking version or kick off a Future
import asyncio
def wrap_coroutine(coroutine):
def future(*a, **kw):
return asyncio.ensure_future(coroutine(*a, **kw))
def sync(*a, **kw):
return asyncio.get_event_loop().run_until_complete(coroutine(*a, **kw))
coroutine.sync = sync
coroutine.future = future
return coroutine
### example
@wrap_coroutine
async def coroutine():
await asyncio.sleep(1)
return 'result'
coroutine() # a coroutine -- execution is deferred
coroutine.future() # a future -- execution starts now
coroutine.sync() # blocks until execution is complete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment