Python はじめました:組み込み関数 compile

《前の記事|記事一覧|次の記事》
Python.use(better)


Python はじめました

■ 組み込み関数 compile
% python3.0
>>> print(compile.__doc__)
compile(source, filename, mode[, flags[, dont_inherit]]) -> code object

Compile the source string (a Python module, statement or expression)
into a code object that can be executed by exec() or eval().
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if non-zero, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or zero these statements do influence the compilation,
in addition to any features explicitly specified.

>>> compile(source="3+4",filename="ex.py",mode="eval")
<code object  at 0xf9608, file "ex.py", line 1>

組み込み関数 compile は、ソースコードコンパイルして、コードオブジェクトを生成します。コードオブジェクトを評価(実行)するには、組み込み関数 eval/exec を利用します。引数 source= には、コードの断片(式/文/モジュール)を指定できます。

>>> code = compile("3+4","example.py","eval"); code
<code object  at 0x68a9f8, file "example.py", line 1>
>>> type(code)

引数 filename= に指定した文字列は(エラーメッセージなどで)コードの断片を含むファイル名を提示したいときに利用します。ファイルに記述されたコードでないとき、慣例では '' を指定します。

>>> eval(code)
7

組み込み関数 eval を利用すると、第1引数に指定した文字列 "3+4" を、Pythonソースコードとして評価して得られる値 7 が、出力されます。

組み込み関数 compile:引数 mode=

キーワード引数 mode= には、次のような文字列を指定できます。

mode
"eval" 単一の式をコンパイルします。
"single" 単一の文をコンパイルします。
"exec" 単一のモジュールをコンパイルします。
>>> eval(compile("3+4","","eval"))
7
>>> eval(compile("3+4","","single"))
7
>>> eval(compile("3+4","","exec"))
    
"single" を指定すると、式を評価した結果が None 以外なら、その値を出力します。
Last updated♪09/03/16