O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

eval(), exec, execfile(), and compile()

The eval(str [,globals [,locals]]) function executes an expression string and returns the result. For example:

a = eval('3*math.sin(3.5+x) + 7.2')

Similarly, the exec statement executes a string containing arbitrary Python code. The code supplied to exec is executed as if the code actually appeared in place of the exec statement. For example:

a = [3, 5, 10, 13]
exec "for i in a: print i"

Finally, the execfile(filename [,globals [,locals]]) function executes the contents of a file. For example:

execfile("foo.py")

All these functions execute within the namespace of the caller (which is used to resolve any symbols that appear within a string or file). Optionally, eval(), exec, and execfile() can accept ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required