python3.7+中是否有默认的空上下文管理器?

c9x0cxw0  于 5个月前  发布在  Python
关注(0)|答案(2)|浏览(60)

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

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

字符串
是否有任何默认的无效上下文管理器?

92vpleto

92vpleto1#

是否有任何默认的无效上下文管理器?
可以使用contextlib.AsyncExitStack()
在引入nullcontext之前,ExitStack()类似地是创建快速而肮脏的空上下文管理器的方法。

pexxcrt2

pexxcrt22#

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

from contextlib import nullcontext

def works():
    with nullcontext():
        pass

async def works_too():
    async with nullcontext():
        pass

字符串
(This这个问题明确提到了Python 3.7,但我猜越来越多的人可能会发现它并不特别需要那个版本,因此这个答案)

相关问题