Exec can execute dynamic Python code, like the Eval function of JavaScript, and the eval function in Python can compute the Python expression and return the result (exec does not return the result, print (eval (...)) prints none);
Copy Code code as follows:
>>> EXEC ("Print (\" Hello, world\ ")")
Hello, world
>>> A = 1
>>> EXEC ("a = 2")
>>> A
2
Here is the concept of scope (namespace, scope), to create a new scope (a dictionary) to perform exec (JavaScript does not have this feature) in order not to break the current scope:
Copy Code code as follows:
>>> scope = {}
>>> EXEC ("a = 4", scope)
>>> A
2
>>> scope[' a ']
4
>>> Scope.keys ()
Dict_keys ([' A ', ' __builtins__ '])
__BUILTINS__ contains all the built-in functions and values;
and the normal {} does not contain __builtins__
Copy Code code as follows:
>>> a = {}
>>> A.keys ()
Dict_keys ([])
As with exec, Eval can also use namespaces:
Copy Code code as follows:
>>> result = eval (' 2+3 ')
>>> result
5
>>> scope={}
>>> scope[' a '] = 3
>>> scope[' b '] = 4
>>> result = eval (' a+b ', scope)
>>> result
7