在一个python事件循环中进行async-sync-async调用

2024-04-27 14:13:34 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个在内部使用asyncio循环但没有异步接口的类:

class Fetcher:
    _loop = None
    def get_result(...):
        """
        After 3 nested sync calls async tasks are finally called with *run_until_complete*
        """
        ...

我在内部使用asyncio的所有优点,而不必在外部代码中考虑它。

但是我想在一个事件循环中调用3个Fetcher实例。如果我有async def接口就不会有问题:asyncio.gather可以帮助我。如果不支持both interfaces,真的没有其他方法可以做到吗?快点!它使您更改所有项目,因为一个异步使用。告诉我这不是真的。


Tags: noneloopasynciogetasyncdefsyncresult
1条回答
网友
1楼 · 发布于 2024-04-27 14:13:34

Come on! It makes you change all your project because of one asyncio usage. Tell me this is not true.

是真的

使用await关键字的整个思想是在一个事件循环中从代码的不同位置执行并发作业(这是常规函数代码所不能做到的)。

asyncio-不是某种实用程序,而是编写异步程序的整体风格。


另一方面,Python非常灵活,因此您仍然可以尝试隐藏使用asyncio。如果您真的想得到3个Fetcher实例的同步结果,例如可以执行以下操作:

import asyncio


def sync_exec(coro):
    loop = asyncio.get_event_loop()
    return loop.run_until_complete(coro)


class Fetcher:
    async def async_get_result(self):
        # async interface:
        async def async_job():
            await asyncio.sleep(1)
            return id(self)
        return (await async_job())

    def get_result(self):
        # sync interface:
        return sync_exec(self.async_get_result())

    @classmethod
    def get_results(cls, *fetchers):
        # sync interface multiple:
        return sync_exec(
            asyncio.gather(*[fetcher.async_get_result() for fetcher in fetchers])
        )        



# single sync get_result:
f1 = Fetcher()
print('Result: ', f1.get_result())


# multiple sync get_result:
f2 = Fetcher()
f3 = Fetcher()
print('Results: ', Fetcher.get_results(f1, f2, f3))

输出:

Result:  2504097887120
Results:  [2504097887120, 2504104854416, 2504104854136]

但是,再次重申,如果你继续这样写代码,相信我,总有一天你会后悔的。如果您想充分利用异步编程的优势,可以显式地使用coroutinesawait

相关问题 更多 >