__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__ 机制的最��议。