Last active
June 4, 2024 00:16
-
-
Save achille-roussel/15e5d3658845c1bbd8c8b1ac99a81a41 to your computer and use it in GitHub Desktop.
Python: custom futures integrating with asyncio event loops
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 | |
from types import coroutine | |
@coroutine | |
def future(value): | |
yield value | |
@coroutine | |
def task(coro): | |
for item in coro.__await__(): | |
if isinstance(item, asyncio.Future): | |
yield item | |
else: | |
return item | |
def hybrid(fn): | |
"""Decorator that wraps a coroutine function to capture all non-asyncio yields.""" | |
async def wrapper(*args, **kwargs): | |
return await task(fn(*args, **kwargs)) | |
return wrapper | |
@hybrid | |
async def work(value): | |
await asyncio.sleep(0.1) | |
await future(value) | |
async def main(): | |
results = await asyncio.gather( | |
asyncio.create_task(work(1)), | |
asyncio.create_task(work(2)), | |
asyncio.create_task(work(3)), | |
asyncio.create_task(work(4)), | |
) | |
print(results) | |
asyncio.run(main()) |
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
$ python custom_future_asyncio.py | |
sleep! | |
sleep! | |
sleep! | |
sleep! | |
[1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment