__future__ --- future 文の定義¶
ソースコード: Lib/__future__.py
__future__ は実物のモジュールであり、次の3つの役割があります:
- import 文を解析する既存のツールを混乱させることを避け、インポートしようとしているモジュールを見つけられるようにするため。 
- 2.1 以前のリリースで future 文 が実行された場合に、最低でもランタイム例外を投げるようにするため ( - __future__のインポートは失敗します。なぜなら、 2.1 以前にはそういう名前のモジュールはなかったからです)。
- 互換性のない変化がいつ言語に導入され、いつ言語の一部になる --- あるいは、なった --- のかを文書化するため。これは実行できる形式で書かれたドキュメントなので、 - __future__をインポートしてその中身を調べることでプログラムから調査することができます。
__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
)
OptionalRelease はその機能が導入された最初のリリースを記録します。
まだ時期が来ていない MandatoryRelease の場合、MandatoryRelease はその機能が言語の一部となるリリースを記します。
その他の場合、MandatoryRelease はその機能がいつ言語の一部になったのかを記録します。そのリリースから、あるいはそれ以降のリリースでは、この機能を使う際に future 文は必要ではありませんが、future 文を使い続けても構いません。
MandatoryRelease は None になるかもしれません。つまり、予定された機能が破棄されたということです。
_Feature クラスのインスタンスには対応する2つのメソッド、 getOptionalRelease() と getMandatoryRelease() があります。
CompilerFlag は、動的にコンパイルされるコードでその機能を有効にするために、組み込み関数 compile() の第4引数に渡す(ビットフィールド)フラグです。このフラグは _Feature インスタンスの compiler_flag 属性に保存されています。
機能の記述が __future__ から削除されたことはまだありません。 Python 2.1 で future 文が導入されて以来、この仕組みを使って以下の機能が言語に導入されてきました:
| feature | optional in | mandatory in | effect | 
|---|---|---|---|
| nested_scopes | 2.1.0b1 | 2.2 | PEP 227: Statically Nested Scopes | 
| generators | 2.2.0a1 | 2.3 | PEP 255: Simple Generators | 
| division | 2.2.0a2 | 3.0 | PEP 238: Changing the Division Operator | 
| absolute_import | 2.5.0a1 | 3.0 | PEP 328: Imports: Multi-Line and Absolute/Relative | 
| with_statement | 2.5.0a1 | 2.6 | PEP 343: The "with" Statement | 
| print_function | 2.6.0a2 | 3.0 | PEP 3105: Make print a function | 
| unicode_literals | 2.6.0a2 | 3.0 | PEP 3112: Bytes literals in Python 3000 | 
| generator_stop | 3.5.0b1 | 3.7 | PEP 479: StopIteration handling inside generators | 
| annotations | 3.7.0b1 | TBD 1 | PEP 563: Postponed evaluation of annotations | 
- 1
- from __future__ import annotationswas 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 statement)
- コンパイラがどのように future インポートを扱うか。