哪个Python版本需要使用__future__导入with_statement?

27

我使用Python 2.6.5版本,可以在不调用from __future__ import with_statement的情况下使用with语句。如何判断哪个版本的Python支持with而无需从__future__中具体导入它?

3个回答

51

__future__特性是自我描述的。请尝试这样做:

>>> from __future__ import with_statement
>>> with_statement.getOptionalRelease()
(2, 5, 0, 'alpha', 1)
>>> with_statement.getMandatoryRelease()
(2, 6, 0, 'alpha', 0)

这些分别表示支持from __future__ import with_statement的第一个版本和支持它而不使用from __future__的第一个版本。

另外,请阅读此内容:

>>> import __future__
>>> help(__future__)

17
您只需要在Python 2.5中使用它。旧版本(<= 2.4)不支持它,而新版本(>= 2.6)默认启用它。
因此,如果您想支持Python> = 2.5,只需在开头添加from __future__ import with_statement即可。对于更新的版本,它将被忽略。

2

文档中的内容:

New in version 2.5.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接