Last active
January 20, 2020 05:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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