exec, eval

□未翻訳

□翻訳中

□翻訳完了(細田謙二)

■レビュー(Omi Chiba)

exec, eval

Javaと異なり、Pythonは真のインタプリンタ言語です。つまり、文字列として格納されたPythonコードを実行する能力があります。例:

Unlike Java, Python is a truly interpreted language. This means it has the ability to execute Python statements stored in strings. For example:

1.

2.

3.

>>> a = "print 'hello world'"

>>> exec(a)

'hello world'

何が起こったのでしょうか?関数execは、インタープリンタに自分自身を呼び出すように命令し、引数として渡された文字列の中身を実行します。また、辞書のシンボルによって定義されたコンテキストの中で、文字列の中身を実行することも可能です:

What just happened? The function exec tells the interpreter to call itself and execute the content of the string passed as argument. It is also possible to execute the content of a string within a context defined by the symbols in a dictionary:

1.

2.

3.

4.

>>> a = "print b"

>>> c = dict(b=3)

>>> exec(a, {}, c)

3

ここでは、インタプリタが、文字列aを実行したときに、cで定義されたシンボル(この例ではb)を参照しています。ただし、cやa自身を参照することはありません。これは制限された環境とは大きく異なります。execは内部コードができることに制限を加えないからです。コードが利用出来る変数セットを単に定義しているだけです。

Here the interpreter, when executing the string a, sees the symbols defined in c (b in the example), but does not see c or a themselves. This is different than a restricted environment, since exec does not limit what the inner code can do; it just defines the set of variables visible to the code.

関連する関数としてevalがあります。これは、execと非常に似た動きをしますが、評価される引数が値になることを想定し、その値を返すという点で異なります。

A related function is eval, which works very much like exec except that it expects the argument to evaluate to a value, and it returns that value.

1.

2.

3.

4.

>>> a = "3*4"

>>> b = eval(a)

>>> print b

12