SoFunction
Updated on 2024-10-29

Examples of using exec, eval in Python

Dynamic Python code can be executed through exec, similar to Javascript's eval function; and the eval function in Python can compute Python expressions and return the result (exec does not return the result, print(eval("...")) prints None);

Copy Code The code is as follows.
  
>>> exec("print(\"hello, world\")")
hello, world

>>> a = 1
>>> exec("a = 2")
>>> a
2

Here there is a scope (namespace, scope) concept, in order not to destroy the existing scope, you can create a new scope (a dictionary) to execute exec (Javascript does not have this feature):

Copy Code The code is as follows.

>>> scope = {}
>>> exec("a = 4", scope)
>>> a
2
>>> scope['a']
4
  
>>> ()
dict_keys(['a', '__builtins__'])

__builtins__ contains all the built-in functions and values;

And a normal {} will not contain __builtins__.

Copy Code The code is as follows.

>>> a = {}
>>> ()
dict_keys([])

Like exec, eval can use namespaces:

Copy Code The code is as follows.

>>> result = eval('2+3')
>>> result
5
>>> scope={}
>>> scope['a'] = 3
>>> scope['b'] = 4
>>> result = eval('a+b',scope)
>>> result
7