我们的代码根据运行时参数调用可变数量的上下文管理器:
from contextlib import nested, contextmanager
@contextmanager
def my_context(arg):
print("entering", arg)
try:
yield arg
finally:
print("exiting", arg)
def my_fn(items):
with nested(*(my_context(arg) for arg in items)) as managers:
print("processing under", managers)
my_fn(range(3))
但是,^{
DeprecationWarning: With-statements now directly support multiple context managers
对Multiple variables in Python 'with' statement的回答表明contextlib.nested
有一些“容易引起混淆的错误的怪癖”,但是建议的使用multiple managerwith
语句的替代方法对于可变数量的上下文管理器不起作用(而且还会破坏向后兼容性)。
除了contextlib.nested
之外,还有没有不被弃用且(最好)没有相同错误的替代品?
还是继续使用contextlib.nested
并忽略警告?如果是,我是否应该计划将来某个时候删除contextlib.nested
?
似乎应该对多个上下文管理器实例使用
with
语句。来自https://pymotw.com/2/contextlib/:
python3维护人员选择打破向后兼容性有点恼火,因为用
ExitStack
实现nested
非常简单:新的Python 3 ^{} class 被添加为
contextlib.nested()
的替代品(参见issue 13585)。它的编码方式可以直接在Python 2中使用:
将其用作上下文管理器,然后随意添加嵌套上下文管理器:
对于您的示例上下文管理器,将打印:
您还可以安装^{} module ;它包含
ExitStack
作为后台端口。相关问题 更多 >
编程相关推荐