Files
wiki/nest-asyncio
2024-11-25 20:08:33 -05:00
..
2024-11-25 20:08:33 -05:00

def sync(coro):
    import asyncio, functools
    if not asyncio.iscoroutinefunction(coro): return coro
    @functools.wraps(coro)
    def wrapper(*args, **kwargs):
        loop, future = asyncio.get_event_loop(), asyncio.ensure_future(coro(*args, **kwargs))
        while not future.done(): 
            loop._process_events(loop._selector.select(0))
            if (ready := loop._ready) and (handle := ready.popleft())._cancelled is False:
                task = (tasks := asyncio.tasks._current_tasks).pop(loop, None)
                handle._run(); tasks[loop] = task
        return future.result()
    return wrapper

@sync
async def hello():
    @sync
    async def world(): print('hello')
    world() or print('world')
hello()
"""
hello
world
"""