我想创建可选的信号量信号量。如果asyncio.Semaphore不支持None值,我决定创建asyncio.Semaphore,如果指定了连接限制,否则-某种虚拟对象有一个contextlib.nullcontext,但它只支持同步with我创建了自己的dummy:
asyncio.Semaphore
None
contextlib.nullcontext
with
@contextlib.asynccontextmanagerasync def asyncnullcontext(): yield None
@contextlib.asynccontextmanager
async def asyncnullcontext():
yield None
字符串是否有任何默认的无效上下文管理器?
92vpleto1#
是否有任何默认的无效上下文管理器?可以使用contextlib.AsyncExitStack()。在引入nullcontext之前,ExitStack()类似地是创建快速而肮脏的空上下文管理器的方法。
contextlib.AsyncExitStack()
nullcontext
ExitStack()
pexxcrt22#
从Python 3.10+开始,contextlib.nullcontext()可以用作同步和异步上下文管理器。
contextlib.nullcontext()
from contextlib import nullcontextdef works(): with nullcontext(): passasync def works_too(): async with nullcontext(): pass
from contextlib import nullcontext
def works():
with nullcontext():
pass
async def works_too():
async with nullcontext():
字符串(This这个问题明确提到了Python 3.7,但我猜越来越多的人可能会发现它并不特别需要那个版本,因此这个答案)
2条答案
按热度按时间92vpleto1#
是否有任何默认的无效上下文管理器?
可以使用
contextlib.AsyncExitStack()
。在引入
nullcontext
之前,ExitStack()
类似地是创建快速而肮脏的空上下文管理器的方法。pexxcrt22#
从Python 3.10+开始,
contextlib.nullcontext()
可以用作同步和异步上下文管理器。字符串
(This这个问题明确提到了Python 3.7,但我猜越来越多的人可能会发现它并不特别需要那个版本,因此这个答案)