Executing Commands and Evaluating Expressions

Python has built-in functions and statements to facilitate this dynamic code evaluation: eval( expression, [globals[, locals]] ) is a built-in function that evaluates a string, and exec expression, [globals[, locals]] is a statement (not a function: no parentheses needed) that executes a string. The following clarifies how it works:

>>> exec "print 'this expression was compiled on the fly' "
this expression was compiled on the fly
>>> exec "x = 3.14"
>>> eval("x + 1")
4.14

Let’s pause for a moment and consider the implications of this code. You could pass a chunk of text to a running Python application, and it’s parsed, compiled, and executed on the fly. In Python, the interpreter is always available. Few languages offer this capability, and it’s what makes Python a good macro language.

Get Python Programming On Win32 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.