27

使用 python 2.6.5,我可以使用该with语句而无需调用from __future__ import with_statement. 我如何知道哪个版本的 Python 支持with而不专门从中导入它__future__

4

3 回答 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__)
于 2010-09-25T02:29:30.803 回答
17

您只需要在 Python 2.5 中使用它。旧版本 (<= 2.4) 不支持它,而新版本 (>= 2.6) 默认启用它。

所以如果你想支持 Python >= 2.5,你可以简单地将 放在from __future__ import with_statement开头。对于较新的版本,它将被忽略。

于 2010-09-25T00:38:51.803 回答
2

从文档:

New in version 2.5.
于 2010-09-25T00:39:08.840 回答