def sync(obj):
import asyncio, nest_asyncio; nest_asyncio.apply()
if asyncio.iscoroutine(obj): return asyncio.run(obj)
if asyncio.iscoroutinefunction(func := obj):
return lambda *args, **kwargs: sync(func(*args, **kwargs))
for attr in dir(obj):
if asyncio.iscoroutinefunction(method := getattr(obj, attr)):
setattr(obj, attr, sync(method))
return obj
async def foo(): return 42
sync(foo()), sync(foo)()
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
"""