Dynamic code execution with exec and eval
suggest changeSyntax
- eval(expression[, globals=None[, locals=None]])
- exec(object)
- exec(object, globals)
- exec(object, globals, locals)
Parameters
expression
| The expression code as a string, or acode
objectobject
| The statement code as a string, or acode
objectglobals
| The dictionary to use for global variables. If locals is not specified, this is also used for locals. If omitted, theglobals()
of calling scope are usedlocals
| A mapping object that is used for local variables. If omitted, the one passed forglobals
is used instead. If both are omitted, then theglobals()
andlocals()
of the calling scope are used forglobals
andlocals
respectively
Remarks
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:
exec object
exec object in globals
exec object in globals, locals
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents