context.nested 已被弃用,我试图理解这背后的基本原理,在阅读了很长时间的文档后,我看不到一个例子来说明第二个问题:
Secondly, if the
__enter__()method of one of the inner context managers raises an exception that is caught and suppressed by the__exit__()method of one of the outer context managers, this construct will raiseRuntimeErrorrather than skipping the body of thewithstatement.
首先这里的inner context managers和outer context managers是什么意思?这在代码中会是什么样子?
编辑:
根据我的理解,我尝试用代码来证明这个问题:
>>> class A:
... def __enter__(*args):
... print("enter A")
... def __exit__(*args): print("exit A"); return True
...
>>> class B:
... def __enter__(*args): print("B __enter__")
... def __exit__(*args): raise Exception("spam")
...
>>> with nested(A(), B()): pass # A() outer context, B() inner context?
...
enter A
B __enter__
exit A
但是这段代码不会引发RuntimeError?
请您参考如下方法:
在您的示例中,上下文管理器 B 在 __exit__ 方法中引发异常。但是引用描述了 __enter__ 方法引发的内部异常。通过将引发的异常移动到 __enter__ 方法,我能够重现 RuntimeError。
FWIW,contextlib.nested 的替代品是 ExitStack在 python 3.4+ 中。有一个 backport对于 python2。
