python - 以 Python 2.6-/Python 3 中立的方式提示嵌套上下文管理器?

标签 python python-3.x python-2.6 contextmanager

我一直在使用大量上下文管理器作为一种简洁的方式来组合各种设置/拆卸情况。由于我的部署目标是 Python 2.6,这意味着使用 contextlib.nested

最近我对使用相同的代码库同时支持 Python 2.x 和 Python 3 很感兴趣。 some projects 可以做到这一点,但我在上下文管理器的情况下遇到了麻烦,因为:

  1. contextlib.nested 不支持 Python 3
  2. 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 using nested() 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 raise RuntimeError rather than skipping the body of the with statement.

因此在几乎所有情况下,正确答案都是 JBernardo 的。它缩进了一点,但错误也少了一点。

关于python - 以 Python 2.6-/Python 3 中立的方式提示嵌套上下文管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19126182/

相关文章:

python - 带有 flat=True 的 Values_list 仍显示括号

python - 划掉打印值的行 : Python 3

plone - TypeError : expected string or Unicode object, NoneType found - 多处理池在 Zope/Plone 外部方法中不起作用

py2exe - 在 python 2.6 上加载 win32file.pyd 的问题

python - 让 python 应用程序访问存储在 Windows 证书管理器中的证书

python - Boost Python用默认参数包装静态成员函数重载

Python utf-8 字符范围

python - 我如何在 python 2.6 中测试抽象方法

python - 在 python 3 中使用套接字库(RFCOMM 模式)重新连接蓝牙设备?

python - 将字典元素附加到空的 Pandas Dataframe 列中