The eval (), EXEC () two functions in Python and several functions associated with them, such as Globals (), locals (), and compile ():
1. Functions of the Eval function:
Evaluates the value of the specified expression. That is, the Python code it executes can only be a single operation expression (note that Eval does not support arbitrary assignment operations), rather than complex code logic, which is similar to a lambda expression.
function definition:
eval(expression, globals=None, locals=None)
Parameter description:
- Expression: A required parameter, either a string or an arbitrary instance of the Code object (which can be created through the compile function). If it is a string, it is parsed and interpreted as a Python expression (using the Globals and locals parameters as global and local namespaces).
- Globals: An optional parameter that represents the global namespace (which holds the global variable) and, if provided, a Dictionary object.
- Locals: An optional parameter that represents the current local namespace (which holds local variables) and, if provided, can be any mapping object. If the parameter is ignored, then it will take the same value as globals.
- If both globals and locals are ignored, they will take the global namespace and local namespace of the eval () function called environment.
return value:
- If expression is a code object, and when the code object is created, the mode parameter of the compile function is ' exec ', then the return value of the eval () function is none;
- Otherwise, if expression is an output statement, such as print (), eval () returns a result of none;
- Otherwise, the result of expression expressions is the return value of the eval () function;
Instance:
x =10Deffunc (): y = 20 a = eval ( ' x + y ') print ( ' A: ', a) b = eval ( ' x + y ', { ' x ': 1, ' y ': 2}) print ( b: ', b) c = eval ( ' x + y ', { ' x ': 1, ' y ': 2}, { y ': 3, ' Z ': 4}) Print (" C: ', c) d = eval ( ' d: ', D) func ( )
Output Result:
a: 30b: 3c: 410 20d: None
Explanation of the output results:
- The globals and locals parameters of the variable a,eval function are ignored, so both the variable x and the variable y are obtained from the variable values in the scope of the Eval function's called environment, namely: X = ten, y = 20,a = x + y = 30
- For the variable B,eval function only provides the Globals parameter and ignores the locals parameter, so locals takes the value of the Globals parameter, namely: x = 1, y = 2,b = x + y = 3
- For the globals parameter and locals of the variable c,eval function are provided, then the Eval function finds the variable x from the full scope globals and finds the variable y from the local scope locals, namely: x = 1, y = 3, c = x + y = 4
- For variable d, because the print () function is not a calculation expression, no result is evaluated, so the return value is None
2. Functions of the EXEC function:
Execute Python code dynamically. This means that exec can execute complex python code, unlike the Eval function, which only evaluates to the value of an expression.
function definition:
exec(object[, globals[, locals]])
Parameter description:
- Object: A required parameter that represents the python code that needs to be specified. It must be a string or a code object. If object is a string, the string is first parsed into a set of Python statements and then executed (unless a syntax error occurs). If object is a code object, it is simply executed.
- Globals: Optional parameter, same as eval function
- Locals: optional parameter, same as eval function
return value:
The return value of the EXEC function is always none.
It should be explained that exec is not a function in Python 2, but rather a built-in statement (statement), but there is a execfile () function in Python 2. It can be understood that Python 3 combines the functionality of the EXEC statement and execfile () functions into a new EXEC () function:
The eval () function differs from the EXEC () function:
- The eval () function evaluates only the values of a single expression, and the Exec () function can run code snippets on the fly.
- The eval () function can have a return value, and the EXEC () function return value is always none.
Example 1:
Let's replace the Eval function in Example 1 with the EXEC function:
x =10Deffunc (): y = 20 a = EXEC ( ' x + y ') print ( ' A: ', a) b = exec ( ' x + y ', { ' x ': 1, ' y ': 2}) print ( ' B: ', b) c = EXEC ( ' x ': 1, ' y ': 2}, { y ': 3, ' Z ': 4}) Print (" C: ', c) d = EXEC ( ' d: ', D) func ( )
Output Result:
a: Noneb: Nonec: None10 20d: None
As we have said, the return value of the EXEC function is always none.
Example 2:
10expr = """z = 30sum = x + y + zprint(sum)"""def func(): y = 20 exec(expr) exec(expr, {‘x‘: 1, ‘y‘: 2}) exec(expr, {‘x‘: 1, ‘y‘: 2}, {‘y‘: 3, ‘z‘: 4}) func()
Output Result:
603334
Explanation of the output results:
The first two outputs, as explained above, do not explain too much, just as the Eval function does. For the last number 34, we can see that: x = 1, y = 3 is no doubt. About Z is still 30 instead of 4, which is actually very simple, we just need to understand the code execution process is possible, the execution process is equivalent to:
1y = 2def func(): y = 3 z = 4 z = 30 sum = x + y + z print(sum)func()
3. Globals () and locals () function function definition and function Description:
Let's take a look at the definitions and document descriptions of these two functions
Description: Return A dictionary representing the current global symbol table. The dictionary of the current module (inside a function or method, the module where it is defined, The module from which it is called).
Translate: Returns a dictionary representing the current global identifier table. This is always a dictionary of the current module (within a function or method, this is the module that defines the function or method, not the module that calls the function or method)
locals()
Description: Update and return a dictionary representing the current local symbol table. Free variables was returned by locals () when it was called in function blocks, and not in class blocks.
Note The contents of this dictionary should is not being modified; Changes affect the values of the local and free variables used by the interpreter.
translation: updates and returns a dictionary representing the current local identifier table. When a free variable is called inside a function, it is returned by the locals () function, and the free variable is not returned by the locals () function when the class is tired from being called.
Note: the contents of the dictionary returned by locals () should not be changed, and if it must be changed, it should not affect the local variables and free variables used by the interpreter.
Summarize:
- The Globals () function returns all identifiers (variables, constants, etc.) under the global scope within the module that defines the function in the form of a dictionary.
- The locals () function returns all identifiers under the local scope within the current function in the form of a dictionary
- If you call the Globals () and locals () functions directly in the module, their return values are the same
Example 1:
‘Tom‘age = 18def func(x, y): sum = x + y _G = globals() _L = locals() print(id(_G), type(_G), _G) print(id(_L), type(_L), _L)func(10, 20)
Output Result:
2131520814344 <class' Dict ' > {' __builtins__ ': <module' Builtins ' (built-in);' Func ': <function Func at0x000001f048c5e048>,' __doc__ ': None,' __file__ ':' c:/users/wader/pycharmprojects/learnpython/day04/func5.py ',' __loader__ ': <_frozen_importlib_external. Sourcefileloader Object at0x000001f048bf4c50>,' __spec__ ': None,' Age ':18,' __name__ ':' __main__ ',' Name ':' Tom ',' __package__ ': None,' __cached__ ': None}2131524302408 <class' Dict ' > {' Y ':20,' X ':10,' _g ': {' __builtins__ ': <module' Builtins ' (built-in); ' func ': <function func at 0x000001f048c5e048>, ' __doc__ ': None, ' __file__ ': ' c:/users/wader/pycharmprojects/learnpython/day04/func5.py ', 0X000001F048BF4C50>, ' __spec__ ': None, ' age ': 18, ' __name__ ': ' __main__ ', ' name ': ' Tom ', __package__ ': none, ' __cached__ ': none}, ' sum ': Span class= "Hljs-number" >30}
Example 2:
name = ‘Tom‘age = 18G = globals()L = locals()print(id(G), type(G), G)print(id(L), type(L), L)
Output Result:
2494347312392 <class' Dict ' > {' __file__ ':' c:/users/wader/pycharmprojects/learnpython/day04/func5.py ',' __loader__ ': <_frozen_importlib_external. Sourcefileloader Object at0x00000244c2e44c50>,' Name ':' Tom ',' __spec__ ': None,' __builtins__ ': <module' Builtins ' (built-in);' __cached__ ': None,' L ': {...},' __package__ ': None,' __name__ ':' __main__ ',' G ': {...},' __doc__ ': None,' Age ':18}2494347312392 <class' Dict ' > {' __file__ ':' c:/users/wader/pycharmprojects/learnpython/day04/func5.py ', ' __loader__ ': <_frozen_importlib_external. Sourcefileloader object at 0X00000244C2E44C50>, ' name ': Span class= "hljs-string" > ' Tom ', ' __spec__ ': None, ' __builtins_ _ ': <module ' builtins ' (Built-in); ' __cached__ ': None, ' L ': { ...}, Span class= "hljs-string" > ' __package__ ': None, ' __name__ ': ...}, ' __doc__ ': None, ' age ': 18}
The memory addresses of the G and L printed above are the same, stating that the return value of locals () at the module level and the return value of globals () are the same.
4. Functions of the Compile function:
Compiles source to a code object or an AST object. The code object can be evaluated using the EXEC () function or by using the eval () function.
function definition:
compile(source, filename, mode[, flags[, dont_inherit]])
Parameter description:
- Source: A string or AST (Abstract Syntax Trees) object that represents the python code that needs to be compiled
- FileName: Specifies the name of the code file that needs to be compiled, and passes some recognizable values (usually ' <string> ') if the code is not read from the file
- Mode: Used to identify the code that must be compiled as such, and if source is composed of a sequence of code statements, specify mode= ' exec '; specify mode= ' eval ' if source is composed of a single expression If source is composed of a separate interactive statement, specify Mode= ' single '.
- The other two optional parameters are not introduced at this stage.
Instance:
"""for x in range(10): print(x, end=‘‘)print()"""code_exec = compile(s, ‘<string>‘, ‘exec‘)code_eval = compile(‘10 + 20‘, ‘<string>‘, ‘eval‘)code_single = compile(‘name = input("Input Your Name: ")‘, ‘<string>‘, ‘single‘)a = exec(code_exec)b = eval(code_eval)c = exec(code_single)d = eval(code_single)print(‘a: ‘, a)print(‘b: ‘, b)print(‘c: ‘, c)print(‘name: ‘, name)print(‘d: ‘, d)print(‘name; ‘, name)
Output Result:
0123456789Input Your Name: TomInput Your Name: Jerrya: Noneb: 30c: Nonename: Jerryd: Nonename; Jerry
5. The relationship of the several functions
The return result of the comiple () function, globals () function, locals () function can be used as the Eval () function with the parameters of the exec () function.
In addition, we can determine whether a global variable already exists (defined) by judging whether a key is included in the return value of the Globals () function.
Eval (), exec () and its related functions in Python