exec, eval

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

  1. >>> a = "print 'hello world'"
  2. >>> exec(a)
  3. 'hello world'

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. >>> a = "print b"
  2. >>> c = dict(b=3)
  3. >>> exec(a, {}, c)
  4. 3

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.

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. >>> a = "3*4"
  2. >>> b = eval(a)
  3. >>> print b
  4. 12