On this page
28.11. _Future__ —将来的语句定义
源代码: Lib/future.py
future是一个真实的模块,具有三个目的:
为了避免混淆分析导入语句并期望找到要导入的模块的现有工具。
为确保future statements在 2.1 之前的版本中运行至少会产生运行时异常(future的导入将失败,因为在 2.1 之前没有该名称的模块)。
记录何时引入了不兼容的更改,以及何时将它们(或曾经被)强制执行。这是可执行文档的一种形式,可以pass导入future并检查其内容来以编程方式进行检查。
__future__.py
中的每个语句的格式为:
FeatureName = _Feature(OptionalRelease, MandatoryRelease,
CompilerFlag)
通常,其中* OptionalRelease 小于 MandatoryRelease *,并且都是 5Tuples,其形式与sys.version_info
相同:
(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
)
- OptionalRelease *记录接受该Function的第一个发行版。
如果尚未发生* MandatoryRelease ,则 MandatoryRelease *会预测该Function将成为语言一部分的版本。
其他强制发布记录Function何时成为语言的一部分;在那时或之后的版本中,模块不再需要将来的语句来使用所涉及的Function,而是可以 continue 使用此类导入。
- MandatoryRelease *也可能是
None
,表示已删除计划中的Function。
_Feature
类的实例具有两个相应的方法getOptionalRelease()
和getMandatoryRelease()
。
- CompilerFlag *是(位域)标志,应该在第四个参数中传递给内置函数compile()以在动态编译的代码中启用该Function。此标志存储在
_Feature
个实例的compiler_flag
属性中。
从future不会删除任何Function描述。自从 Python 2.1 引入以来,以下Function已使用此机制进入了语言:
feature | optional in | mandatory in | effect |
---|---|---|---|
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:打印Function |
unicode_literals | 2.6.0a2 | 3.0 | PEP 3112:* Python 3000 中的字节字面量* |
See also
编译器如何处理将来的导入。