__future__ --- Future 语句定义

源代码: Lib/__future__.py


from __future__ import feature 形式的导入被称为 future 语句。 它们会被 Python 编译器当作特例,通过包含 future 语句来允许新的 Python 特性在该特性成为语言标准之前发布的模块中使用。

While these future statements are given additional special meaning by the Python compiler, they are still executed like any other import statement and the __future__ exists and is handled by the import system the same way any other Python module would be. This design serves three purposes:

  • 避免混淆已有的分析 import 语句并查找 import 的模块的工具。

  • To document when incompatible changes were introduced, and when they will be --- or were --- made mandatory. This is a form of executable documentation, and can be inspected programmatically via importing __future__ and examining its contents.

  • To ensure that future statements run under releases prior to Python 2.1 at least yield runtime exceptions (the import of __future__ will fail, because there was no module of that name prior to 2.1).

模块内容

No feature description will ever be deleted from __future__. Since its introduction in Python 2.1 the following features have found their way into the language using this mechanism:

特性

可选版本

强制加入版本

效果

__future__.nested_scopes

2.1.0b1

2.2

PEP 227: 静态嵌套作用域

__future__.generators

2.2.0a1

2.3

PEP 255: 简单生成器

__future__.division

2.2.0a2

3.0

PEP 238: 修改除法运算符

__future__.absolute_import

2.5.0a1

3.0

PEP 328: 导入:多行与绝对/相对

__future__.with_statement

2.5.0a1

2.6

PEP 343: * “with” 语句*

__future__.print_function

2.6.0a2

3.0

PEP 3105: print 改为函数

__future__.unicode_literals

2.6.0a2

3.0

PEP 3112: Python 3000 中的字节字面值

__future__.generator_stop

3.5.0b1

3.7

PEP 479: 在生成器中处理 StopIteration

__future__.annotations

3.7.0b1

从不 [1]

PEP 563: 延迟标注求值, PEP 649: 使用描述器的标注延迟求值

class __future__._Feature

__future__.py 中的每一条语句都是以下格式的:

FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                       CompilerFlag)

通常 OptionalRelease 要比 MandatoryRelease 小,并且都是和 sys.version_info 格式一致的 5 元素元组。

(PY_MAJOR_VERSION, # 2.1.0a3 中的 2; 一个整数
 PY_MINOR_VERSION, # 1; 一个整数
 PY_MICRO_VERSION, # 0; 一个整数
 PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" 或 "final"; 字符串
 PY_RELEASE_SERIAL # 3; 一个整数
)
_Feature.getOptionalRelease()

OptionalRelease 记录了一个特性首次发布时的 Python 版本。

_Feature.getMandatoryRelease()

MandatoryRelases 还没有发布时,MandatoryRelease 表示该特性会变成语言的一部分的预测时间。

其他情况下,MandatoryRelease 用来记录这个特性是何时成为语言的一部分的。从该版本往后,使用该特性将不需要 future 语句,不过很多人还是会加上对应的 import。

MandatoryRelease 也可能为 None,表示计划中的特性被撤销或尚未确定。

_Feature.compiler_flag

CompilerFlag 是一个(位)旗标,对于动态编译的代码应当将其作为第四个参数传给内置函数 compile() 以启用相应的特性。 该旗标存储在 _Feature 实例的 _Feature.compiler_flag 属性中。

参见

future 语句

编译器怎样处理 future import。

PEP 236 - 回到 __future__

有关 __future__ 机制的最初提议。