__future__
--- Future 語(yǔ)句定義?
源代碼: Lib/__future__.py
__future__
是一個(gè)真正的模塊,這主要有 3 個(gè)原因:
避免混淆已有的分析 import 語(yǔ)句并查找 import 的模塊的工具。
確保 future 語(yǔ)句 在 2.1 之前的版本運行時(shí)至少能拋出 runtime 異常(import
__future__
會(huì )失敗,因為 2.1 版本之前沒(méi)有這個(gè)模塊)。當引入不兼容的修改時(shí),可以記錄其引入的時(shí)間以及強制使用的時(shí)間。這是一種可執行的文檔,并且可以通過(guò) import
__future__
來(lái)做程序性的檢查。
__future__.py
中的每一條語(yǔ)句都是以下格式的:
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
)
OptionalRelease 記錄了一個(gè)特性首次發(fā)布時(shí)的 Python 版本。
在 MandatoryRelases 還沒(méi)有發(fā)布時(shí),MandatoryRelease 表示該特性會(huì )變成語(yǔ)言的一部分的預測時(shí)間。
其他情況下,MandatoryRelease 用來(lái)記錄這個(gè)特性是何時(shí)成為語(yǔ)言的一部分的。從該版本往后,使用該特性將不需要 future 語(yǔ)句,不過(guò)很多人還是會(huì )加上對應的 import。
MandatoryRelease 也可能是 None
, 表示這個(gè)特性已經(jīng)被撤銷(xiāo)。
_Feature
類(lèi)的實(shí)例有兩個(gè)對應的方法,getOptionalRelease()
和 getMandatoryRelease()
。
CompilerFlag 是一個(gè)(位)標記,對于動(dòng)態(tài)編譯的代碼,需要將這個(gè)標記作為第四個(gè)參數傳入內建函數 compile()
中以開(kāi)啟對應的特性。這個(gè)標記存儲在 _Feature
類(lèi)實(shí)例的 compiler_flag
屬性中。
__future__
中不會(huì )刪除特性的描述。從 Python 2.1 中首次加入以來(lái),通過(guò)這種方式引入了以下特性:
特性 |
可選版本 |
強制加入版本 |
效果 |
---|---|---|---|
nested_scopes |
2.1.0b1 |
2.2 |
PEP 227: 靜態(tài)嵌套作用域 |
generators |
2.2.0a1 |
2.3 |
PEP 255: 簡(jiǎn)單生成器 |
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" 語(yǔ)句* |
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 |
- 1
from __future__ import annotations
was previously scheduled to become mandatory in Python 3.10, but the Python Steering Council twice decided to delay the change (announcement for Python 3.10; announcement for Python 3.11). No final decision has been made yet. See also PEP 563 and PEP 649.
參見(jiàn)
- future 語(yǔ)句
編譯器怎樣處理 future import。