__future__ --- Future 语�定义¶

�代�: Lib/__future__.py


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

虽然这些future 语�被 Python 编译器赋予了�外的特殊�义,但它们�然�会其他导入语�一样被执行,而 __future__ 的存在和被导入系统处�的方�与其他任何 Python 模�的相�。 这�设计有三个目的:

  • é�¿å…�混淆已有的分æž� import 语å�¥å¹¶æŸ¥æ‰¾ import 的模å�—的工具。

  • 当引入ä¸�兼容的修改时,å�¯ä»¥è®°å½•其引入的时间以å�Šå¼ºåˆ¶ä½¿ç”¨çš„æ—¶é—´ã€‚这是一ç§�å�¯æ‰§è¡Œçš„æ–‡æ¡£ï¼Œå¹¶ä¸”å�¯ä»¥é€šè¿‡ import __future__ æ�¥å�šç¨‹åº�性的检查。

  • ç¡®ä¿� future 语å�¥ 在 Python 2.1 之å‰�çš„å�‘布版上è¿�行时至少能抛出è¿�行时异常(对 __future__ 的导入将失败,因为will fail, because there was no module of that name prior to 2.1 之å‰�没有这个模å�—å��称)。

模�内容¶

__future__ 中�会删除特性的�述。从 Python 2.1 中首次加入以�,通过这�方�引入了以下特性:

特性

�选版本

强制加入版本

效果

nested_scopes

2.1.0b1

2.2

PEP 227: ��嵌套作用域

generators

2.2.0a1

2.3

PEP 255: 简�生�器

division

2.2.0a2

3.0

PEP 238: 修改除法�算符

absolute_import

2.5.0a1

3.0

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

with_statement

2.5.0a1

2.6

PEP 343: * "with" 语�*

print_function

2.6.0a2

3.0

PEP 3105: print 改为函数

unicode_literals

2.6.0a2

3.0

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

generator_stop

3.5.0b1

3.7

PEP 479: 在生�器中处� StopIteration

annotations

3.7.0b1

TBD [1]

PEP 563: Postponed evaluation of annotations

class __future__._Feature¶

__future__.py 中的�一�语�都是以下格�的:

FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                       CompilerFlag)

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

(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
 PY_MINOR_VERSION, # the 1; an int
 PY_MICRO_VERSION, # the 0; an int
 PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
 PY_RELEASE_SERIAL # the 3; an int
)
_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__ 机制的最��议。