Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book