__future__ --- Future 語句定義?

源代碼: Lib/__future__.py


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

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

  • 確保 future 語句 在 2.1 之前的版本運(yùn)行時(shí)至少能拋出 runtime 異常(import __future__ 會(huì)失敗,因?yàn)?2.1 版本之前沒有這個(gè)模塊)。

  • 當(dāng)引入不兼容的修改時(shí),可以記錄其引入的時(shí)間以及強(qiáng)制使用的時(shí)間。這是一種可執(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 記錄了一個(gè)特性首次發(fā)布時(shí)的 Python 版本。

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

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

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

_Feature 類的實(shí)例有兩個(gè)對(duì)應(yīng)的方法,getOptionalRelease()getMandatoryRelease()。

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

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

特性

可選版本

強(qiáng)制加入版本

效果

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: 修改除法運(yùn)算符

absolute_import

2.5.0a1

3.0

PEP 328: 導(dǎo)入:多行與絕對(duì)/相對(duì)

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。