Learn python (ten)-eval() and exec() functions

Both eval() and exec() functions are  built-in functions of  Python , because these two functions have similarities in function and usage. The functions of the eval() and exec() functions are similar. Both can execute a Python code in the form of a string (the code is provided in the form of a string), which is equivalent to a Python interpreter. The difference between the two is that eval() returns a result after execution, while exec() does not return a result after execution.

 

The syntax format of the eval() function is: eval(source, globals=None, locals=None, /); and the syntax format of the exec() function is as follows: exec(source, globals=None, locals=None, /).

  • expression: This parameter is a string representing the statement to be executed. This statement is restricted by the following two dictionary type parameters globals and locals. Only functions and variables within the scope of the globals dictionary and locals dictionary can be executed.
  • globals: This parameter controls a global namespace, that is, expression can use functions in the global namespace. If only the globals parameter is provided, but no custom __builtins__ is provided, the system will copy the __builtins__ in the current environment to the globals provided by itself, and then perform the calculation; if even the globals parameter is not provided, Use Python's global namespace.
  • locals: This parameter controls a local namespace, which is similar to globals. When it overlaps or conflicts with globals, the locals shall prevail. If locals are not provided, it defaults to globals.

Note that __builtins__ is a built-in module of Python, and the usual int, str, and abs are all in this module. You can view the value corresponding to __builtins__ through the print(dic["__builtins__"]) statement.

When using Python to develop server-side programs, these two functions are widely used. For example, if the client sends a string of code to the server, the server does not need to care about the specific content, and skips eval() or exec() to execute it. This design makes the coupling between the server and the client lower, and the system Easier to expand.

Guess you like

Origin blog.csdn.net/qq_35789421/article/details/113572239