Python Language Dynamic code execution with `exec` and `eval`


  • eval(expression[, globals=None[, locals=None]])
  • exec(object)
  • exec(object, globals)
  • exec(object, globals, locals)


expressionThe expression code as a string, or a code object
objectThe statement code as a string, or a code object
globalsThe dictionary to use for global variables. If locals is not specified, this is also used for locals. If omitted, the globals() of calling scope are used.
localsA mapping object that is used for local variables. If omitted, the one passed for globals is used instead. If both are omitted, then the globals() and locals() of the calling scope are used for globals and locals respectively.


In exec, if globals is locals (i.e. they refer to the same object), the code is executed as if it is on the module level. If globals and locals are distinct objects, the code is executed as if it were in a class body.

If the globals object is passed in, but doesn't specify __builtins__ key, then Python built-in functions and names are automatically added to the global scope. To suppress the availability of functions such as print or isinstance in the executed scope, let globals have the key __builtins__ mapped to value None. However, this is not a security feature.

The Python 2 -specific syntax shouldn't be used; the Python 3 syntax will work in Python 2. Thus the following forms are deprecated: <s>

  • exec object
  • exec object in globals
  • exec object in globals, locals