Python compile() 関数

Python 内置函数Python 組み込み関数


説明

compile() 関数は、文字列をバイトコードにコンパイルします。

構文

以下は compile() 関数の構文です:

compile(source, filename, mode[, flags[, dont_inherit]])

パラメータ

  • source -- 文字列またはAST(Abstract Syntax Trees)オブジェクト。
  • filename -- コードファイル名。ファイルからコードを読み取らない場合は、認識可能な値を渡します。
  • mode -- コンパイルするコードの種類を指定します。exec、eval、single を指定できます。
  • flags -- 変数スコープ、ローカル名前空間。提供される場合、任意のマッピングオブジェクトを指定できます。
  • flags と dont_inherit は、ソースコードをコンパイルする際のフラグを制御するために使用されます。

戻り値

式の実行結果を返します。


例

以下は compile 関数を使用した例です:

>>>str = "for i in range(0,10): print(i)" >>> c = compile(str,'','exec') # バイトコードオブジェクトにコンパイルする >>> c <code object <module> at 0x10141e0b0, file "", line 1> >>> exec(c) 0 1 2 3 4 5 6 7 8 9 >>> str = "3 * 4 + 5" >>> a = compile(str,'','eval') >>> eval(a) 17

Python 内置函数Python 組み込み関数

その他の拡張