eval(),exec, execfile() and compile() functions in Python

05 min read

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 arbitary 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("face.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 the syntax
execfile("face.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 of a function body may result in a Syntaxerror exception if that function also contains nested function definitions or uses the lambda operator.

 

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. The kind argument specifies the type of code compiled i.e '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
str2 = "3*x + 4*y"
c2 = compile(str2, ' ', 'eval') #compile intoan expression
result = eval(c2) # execute
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error