python3.7+中是否有默认的异步null上下文管理器



我想创建可选的异步信号量
如果asyncio.Semaphore不支持None值,我决定创建asyncio.Semaphore,如果指定了连接限制,否则-某种伪对象
有一个contextlib.nullcontext,但它只支持同步的with
我已经创建了自己的伪对象:

@contextlib.asynccontextmanager
async def asyncnullcontext():
yield None

有没有默认的异步null上下文管理器?

是否有默认的异步null上下文管理器?

您可以使用contextlib.AsyncExitStack()

ExitStack()类似于在引入nullcontext之前创建快速且脏的空上下文管理器的方法。

从Python 3.10+开始,contextlib.nullcontext()既可以用作同步上下文管理器,也可以用作异步上下文管理器。

from contextlib import nullcontext
def works():
with nullcontext():
pass
async def works_too():
async with nullcontext():
pass

(这个问题明确提到了Python 3.7,但我想越来越多的人可能会在不需要该版本的情况下找到它,因此给出了这个答案(

最新更新