__future__ --- Future 語句定義?

源代碼: Lib/__future__.py


__future__ 是一個真正的模塊,這主要有 3 個原因:

  • 避免混淆已有的分析 import 語句并查找 import 的模塊的工具。

  • 確保 future 語句 在 2.1 之前的版本運行時至少能拋出 runtime 異常(import __future__ 會失敗,因為 2.1 版本之前沒有這個模塊)。

  • 當引入不兼容的修改時,可以記錄其引入的時間以及強制使用的時間。這是一種可執(zhí)行的文檔,并且可以通過 import __future__ 來做程序性的檢查。

__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
)

OptionalRelease 記錄了一個特性首次發(fā)布時的 Python 版本。

MandatoryRelases 還沒有發(fā)布時,MandatoryRelease 表示該特性會變成語言的一部分的預(yù)測時間。

其他情況下,MandatoryRelease 用來記錄這個特性是何時成為語言的一部分的。從該版本往后,使用該特性將不需要 future 語句,不過很多人還是會加上對應(yīng)的 import。

MandatoryRelease 也可能是 None, 表示這個特性已經(jīng)被撤銷。

_Feature 類的實例有兩個對應(yīng)的方法,getOptionalRelease()getMandatoryRelease()。

CompilerFlag 是一個(位)標記,對于動態(tài)編譯的代碼,需要將這個標記作為第四個參數(shù)傳入內(nèi)建函數(shù) compile() 中以開啟對應(yīng)的特性。這個標記存儲在 _Feature 類實例的 compiler_flag 屬性中。

__future__ 中不會刪除特性的描述。從 Python 2.1 中首次加入以來,通過這種方式引入了以下特性:

特性

可選版本

強制加入版本

效果

nested_scopes

2.1.0b1

2.2

PEP 227: 靜態(tài)嵌套作用域

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: 導(dǎo)入:多行與絕對/相對

with_statement

2.5.0a1

2.6

PEP 343: * "with" 語句*

print_function

2.6.0a2

3.0

PEP 3105: print 改為函數(shù)

unicode_literals

2.6.0a2

3.0

PEP 3112: Python 3000 中的字節(jié)字面值

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.

參見

future 語句

編譯器怎樣處理 future import。