Linux/Unix > Python Essential Reference, Second Edition > 6. Functions and Functional Programming > eval() , exec , execfile() , and compile() | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104017178091035069051057

### `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 within the namespace of the caller 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 one or two dictionaries that serve as the global and local namespaces for the code to be executed, respectively. For example:

    globals = {'x': 7,
               'y': 10,
               'birds': ['Parrot', 'Swallow', 'Albatross']
              }

    locals = { }

    # Execute using the above dictionaries as the global and local namespace
    a = eval("3*x + 4*y", globals, locals)
    exec "for b in birds: print b" in globals, locals   # Note unusual syntax
    execfile("foo.py", globals, locals)

If you omit one or both namespaces, the current values of the global and local namespaces are used. Also, due to issues related to nested scopes, the use of `exec` or `execfile()` inside a function body may result in a `SyntaxError` exception if that function also contains nested function definitions or uses the `lambda` operator.

Note that the syntax of the `exec` statement in the example is different from that of `eval()` and `execfile()`. `exec` is a statement (much like `print` or `while`), whereas `eval()` and `execfile()` are built-in functions.

When a string is passed to `exec`, `eval()`, or `execfile()`, the parser first compiles it into bytecode. Because this process is expensive, it may be better to precompile the code and reuse the bytecode on subsequent calls if the code will be executed multiple times.

The `compile(``str` `,``filename` `,``kind` `)` function compiles a string into bytecode in which `str` is a string containing the code to be compiled and `filename` is the file in which the string is defined (for use in traceback generation). The `kind` argument specifies the type of code being compiled— `'single'` for a single statement, `'exec'` for a set of statements, or `'eval'` for an expression. The code object returned by the `compile()` function can also be passed to the `eval()` function and `exec` statement. For example:

    str = "for i in range(0,10): print i"
    c = compile(str,"','exec')      # Compile into a code object
    exec c                          # Execute it

    str2 = "3*x + 4*y"
    c2 = compile(str2, '', 'eval')  # Compile into an expression
    result = eval(c2)               # Execute it

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.