Skip to content

Instantly share code, notes, and snippets.

@achille-roussel
Last active June 4, 2024 00:16
Show Gist options
  • Save achille-roussel/15e5d3658845c1bbd8c8b1ac99a81a41 to your computer and use it in GitHub Desktop.
Save achille-roussel/15e5d3658845c1bbd8c8b1ac99a81a41 to your computer and use it in GitHub Desktop.
Python: custom futures integrating with asyncio event loops
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())
$ 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