从Python消除异步污染

问题描述 投票:0回答:1

如何在这样的程序中消除异步到处的疯狂?

import asyncio


async def async_coro():
    await asyncio.sleep(1)


async def sync_func_1():
    # This is blocking and synchronous
    await async_coro()


async def sync_func_2():
    # This is blocking and synchronous
    await sync_func_1()


if __name__ == "__main__":
    # Async pollution goes all the way to __main__
    asyncio.run(sync_func_2())

我需要在顶层具有3个async标记和asyncio.run,才能调用一个异步函数。我认为自己做错了-如何清除此代码以减少异步使用次数?]

FWIW,我最感兴趣的是因为我正在使用asyncio编写API,并且我不希望我的用户根据他们的功能是def还是async def来过分考虑是否正在使用API​​的异步部分。

python python-asyncio api-design
1个回答
0
投票

经过一番研究,一个答案是手动管理事件循环:

import asyncio


async def async_coro():
    await asyncio.sleep(1)


def sync_func_1():
    # This is blocking and synchronous
    loop = asyncio.get_event_loop()
    coro = async_coro()
    loop.run_until_complete(coro)


def sync_func_2():
    # This is blocking and synchronous
    sync_func_1()


if __name__ == "__main__":
    # No more async pollution
    sync_func_2()
© www.soinside.com 2019 - 2024. All rights reserved.