__future__ --- Future 语句定义¶
源代码: Lib/__future__.py
__future__ 是一个真正的模块,这主要有 3 个原因:
- 避免混淆已有的分析 import 语句并查找 import 的模块的工具。 
- 确保 future 语句 在 2.1 之前的版本运行时至少能抛出 runtime 异常(import - __future__会失败,因为 2.1 版本之前没有这个模块)。
- 当引入不兼容的修改时,可以记录其引入的时间以及强制使用的时间。这是一种可执行的文档,并且可以通过 import - __future__来做程序性的检查。
- 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 may also be - None, meaning that a planned feature got dropped or that it is not yet decided.
- _Feature.compiler_flag¶
- CompilerFlag is the (bitfield) flag that should be passed in the fourth argument to the built-in function - compile()to enable the feature in dynamically compiled code. This flag is stored in the- _Feature.compiler_flagattribute on- _Featureinstances.
__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 | 
参见
- future 语句
- 编译器怎样处理 future import。