我一直在使用大量上下文管理器作为一种简洁的方式来组合各种设置/拆卸情况。由于我的部署目标是 Python 2.6,这意味着使用 contextlib.nested
。
最近我对使用相同的代码库同时支持 Python 2.x 和 Python 3 很感兴趣。 some projects 可以做到这一点,但我在上下文管理器的情况下遇到了麻烦,因为:
contextlib.nested
不支持 Python 3- Python-3 风格的嵌套上下文管理器(例如,
with aa() as a, bb() as b: ...
)在 2.6 中不受支持。
这里存在基本的句法不兼容。由于我无法控制的各种原因,2.7 目前可能难以投入生产,但我想尽可能地让代码面向 future ,因此对 Python 3 感兴趣。
谁能建议在 2.6 和 3.x 的同一代码库中支持嵌套上下文管理器的解决方法?或者这是一个失败的原因?
最佳答案
来自文档:
This function has two major quirks that have led to it being deprecated. Firstly, as the context managers are all constructed before the function is invoked, the
__new__()
and__init__()
methods of the inner context managers are not actually covered by the scope of the outer context managers. That means, for example, that usingnested()
to open two files is a programming error as the first file will not be closed promptly if an exception is thrown when opening the second file.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 raiseRuntimeError
rather than skipping the body of the with statement.
因此在几乎所有情况下,正确答案都是 JBernardo 的。它缩进了一点,但错误也少了一点。
关于python - 以 Python 2.6-/Python 3 中立的方式提示嵌套上下文管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126182/