__future__ --- future 文の定義¶
ソースコード: Lib/__future__.py
from __future__ import feature の形式でのインポートは future 文 の定義と呼ばれています。これらは特殊なケースで、 Python の新機能が標準になるリリースの前に Python コンパイラーが future 文を含むモジュールで Python の新機能を使用できるようにします。
While these future statements are given additional special meaning by the
Python compiler, they are still executed like any other import statement and
the __future__ exists and is handled by the import system the same way
any other Python module would be. This design serves three purposes:
import 文を解析する既存のツールを混乱させることを避け、インポートしようとしているモジュールを見つけられるようにするため。
To document when incompatible changes were introduced, and when they will be --- or were --- made mandatory. This is a form of executable documentation, and can be inspected programmatically via importing
__future__and examining its contents.To ensure that future statements run under releases prior to Python 2.1 at least yield runtime exceptions (the import of
__future__will fail, because there was no module of that name prior to 2.1).
モジュールコンテンツ¶
No feature description will ever be deleted from __future__. Since its
introduction in Python 2.1 the following features have found their way into the
language using this mechanism:
feature |
optional in |
mandatory in |
effect |
|---|---|---|---|
|
2.1.0b1 |
2.2 |
PEP 227: Statically Nested Scopes |
|
2.2.0a1 |
2.3 |
PEP 255: Simple Generators |
|
2.2.0a2 |
3.0 |
PEP 238: Changing the Division Operator |
|
2.5.0a1 |
3.0 |
PEP 328: Imports: Multi-Line and Absolute/Relative |
|
2.5.0a1 |
2.6 |
PEP 343: The “with” Statement |
|
2.6.0a2 |
3.0 |
PEP 3105: Make print a function |
|
2.6.0a2 |
3.0 |
PEP 3112: Bytes literals in Python 3000 |
|
3.5.0b1 |
3.7 |
PEP 479: StopIteration handling inside generators |
|
3.7.0b1 |
Never [1] |
PEP 563: Postponed evaluation of annotations, PEP 649: Deferred evaluation of annotations using descriptors |
- class __future__._Feature¶
__future__.pyのそれぞれの文は次のような形式をしています:FeatureName = _Feature(OptionalRelease, MandatoryRelease, CompilerFlag)
ここで、普通は、 OptionalRelease は MandatoryRelease より小さく、2つとも
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 はその機能が導入された最初のリリースを記録します。
- _Feature.getMandatoryRelease()¶
まだ時期が来ていない MandatoryRelease の場合、MandatoryRelease はその機能が言語の一部となるリリースを記します。
その他の場合、MandatoryRelease はその機能がいつ言語の一部になったのかを記録します。そのリリースから、あるいはそれ以降のリリースでは、この機能を使う際に future 文は必要ではありませんが、future 文を使い続けても構いません。
MandatoryRelease は
Noneになるかもしれません。つまり、予定された機能が破棄されたか、まだ決定されていないということです。
- _Feature.compiler_flag¶
CompilerFlag は、動的にコンパイルされるコードでその機能を有効にするために、組み込み関数
compile()の第4引数に渡す(ビットフィールド)フラグです。このフラグは_Featureインスタンスの_Feature.compiler_flag属性に保存されています。
参考
- future 文 (future statement)
コンパイラがどのように future インポートを扱うか。
- PEP 236 - Back to the __future__
__future__ 機構の原案