求解释async的优点with/for
Seeking explanation of the advantages of async with/for
我是 asyncio 的新手。我最近遇到了 AIOFiles (https://github.com/Tinche/aiofiles) 并在文档中看到它支持 'async with' 和 'async for.' 我想了解它但是除了 PEP 492 之外没有太多好的报道这并没有涉及太多细节。
PEP 492 相关部分的快捷方式:
https://www.python.org/dev/peps/pep-0492/#asynchronous-context-managers-and-async-with
https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for
如果有人不介意回答,我有很多问题:
我正在使用的异步迭代器/上下文管理器的唯一明显好处是您可以在其所需魔术方法的实现中使用可等待对象。我是漏掉了什么还是漏掉了什么?
在关于异步上下文管理器的 PEP 492 中,它说 "An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods." 这是指使用 await 调用协程吗?
The only discernible benefit of async iterators / context managers I am picking up on is that you can use awaitables in the implementations of their required magic methods. Am I missing something or is that it?
除了暂停功能的重要性外,您没有遗漏任何东西。如果没有可暂停的魔术方法,上下文管理器和迭代器将无法用于异步工作。例如,一个常规文件对象用作从文件中生成行的迭代器。对于提供等效功能的异步文件对象(或流),它必须能够等待行的到来,从而暂停迭代它的协程。这同样适用于上下文管理器,其进入必须建立异步网络连接等。
Is [being able to suspend execution] referring to calling coroutines using await?
在 async def
中使用 await
是暂停执行的一种方法。另一种选择是 __aenter__
等成为正常函数,return 实现自己的 __await__
的自定义可等待对象。 PEP 492 从使用上下文管理器的代码的有利位置描述了功能,它必须准备好挂起它的魔术方法——async with
必须在 async def
内并且它将脱糖到代码await
在适当的地方。
我是 asyncio 的新手。我最近遇到了 AIOFiles (https://github.com/Tinche/aiofiles) 并在文档中看到它支持 'async with' 和 'async for.' 我想了解它但是除了 PEP 492 之外没有太多好的报道这并没有涉及太多细节。
PEP 492 相关部分的快捷方式:
https://www.python.org/dev/peps/pep-0492/#asynchronous-context-managers-and-async-with
https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for
如果有人不介意回答,我有很多问题:
我正在使用的异步迭代器/上下文管理器的唯一明显好处是您可以在其所需魔术方法的实现中使用可等待对象。我是漏掉了什么还是漏掉了什么?
在关于异步上下文管理器的 PEP 492 中,它说 "An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods." 这是指使用 await 调用协程吗?
The only discernible benefit of async iterators / context managers I am picking up on is that you can use awaitables in the implementations of their required magic methods. Am I missing something or is that it?
除了暂停功能的重要性外,您没有遗漏任何东西。如果没有可暂停的魔术方法,上下文管理器和迭代器将无法用于异步工作。例如,一个常规文件对象用作从文件中生成行的迭代器。对于提供等效功能的异步文件对象(或流),它必须能够等待行的到来,从而暂停迭代它的协程。这同样适用于上下文管理器,其进入必须建立异步网络连接等。
Is [being able to suspend execution] referring to calling coroutines using await?
在 async def
中使用 await
是暂停执行的一种方法。另一种选择是 __aenter__
等成为正常函数,return 实现自己的 __await__
的自定义可等待对象。 PEP 492 从使用上下文管理器的代码的有利位置描述了功能,它必须准备好挂起它的魔术方法——async with
必须在 async def
内并且它将脱糖到代码await
在适当的地方。