Expression methods (that is, exec and Eval methods) that execute a string form of a statement and a string in Python

Source: Internet
Author: User
Tags arithmetic

The former has been thinking of a problem, that is, how to let the user in the graphical interface input code (input code as a string), as part of the code to run, coincides with the Python crawler video tutorial, saw the use of the Eval function, then found the article, solved my question of thinking.

@ article Source: https://my.oschina.net/duhaizhang/blog/66048

Python sometimes requires dynamic creation of Python code, which is then executed as a statement or evaluated as an expression.

EXEC executes the python code stored in the string.

1. The difference between a statement and an expression: An expression is something, a statement is doing something (that is, telling the computer what to do).

For example, 2*2 is 4, while print 2*2 is printing 4. The result of these two lines of code executing in the interactive interpreter is the same, because the interpreter always prints the values of all the expressions. Writing an expression like 2*2 in the program does not print what is displayed, and writing print 2*2 prints 4.

The difference between a statement and an expression is more pronounced when the value is assigned , because the statement is not an expression, so there is no value. If you enter x=2 in the interactive interpreter, you will not print anything, and a new prompt appears immediately. There's nothing going on, but something has changed. The value of x now changes to 3. This is also the general definition of statement attributes: they change things. For example, the assignment statement changes the variable, and the print statement changes the contents of the screen display.

2. Namespace (scope) global variables and local variables

In addition to the global scope, each function will create a new scope. Variables are divided into global variables and local variables, and variables within functions are called local variables and only work in local namespaces.

Reading a global variable inside a function is generally not a problem, it is directly accessible. However, if the name of the local variable or parameter is the same as the global variable name, it cannot be accessed directly because the global variable is masked by the local variable. If you do, you can use the GLOBALS function to get the values of the masked global variables. (Globals returns a dictionary of global variables, locals returns the value of a local variable). For example, if you have a global variable named parameter, then when accessing a global variable inside the Combine (parameter) function, you must use Globals () [' parameter '] for the same name as the parameter. The code is as follows:

def combine(parameter): print parameter+globals()[‘parameter‘]#函数调用parameter="hello"combine("berry")

Above is the method of reading the global variable inside the function, not including the modification. If you want to modify a global variable inside a function, you need to tell the modified value to be a global variable, because the variable is automatically a local variable if the value is assigned to a variable inside the function. Using the global keyword to tell a python function that a variable needs to be modified is a global variable. The code is as follows:

x=1def change_global(n): global x x=x+1

3. Execute string statement exec

If the input exec "print ' Hello '" will print out hello. (Note: In Python 3.0, Exec is a function that is not a statement, so it is called using EXEC (' string statement ').) The exec execution string statement has a security risk because exec can interfere with the namespace, which is to change variables that should not be changed. For example:

As can be seen from the above example, exec interferes with the namespace and changes the value of the sqrt so that it is not a function and becomes 1. This shows that there is a security risk if there is no restriction on exec. Here are the improvement measures.

Action: implemented by adding in <scope>, where <scope> is a dictionary that plays the role of placing the code string namespace. This way, the code that exec executes will only work in the namespace represented by <scope>. Such as:

As you can see from the above code, the EXEC statement executes in the scope namespace and does not affect the sqrt of the current namespace. Scope, while acting as a namespace, is essentially a dictionary, so if you want to know how many variables are in the scope namespace, you can get through Len (scope), and you can get all the variables of the scope namespace through Scope.key ().

4. Eval evaluates a Python expression in the form of a string and returns the value of the result.

The EXEC statement does not return any objects. Eval returns the value of an expression. The following code can create a python calculator:

#Python计算器print eval(raw_input("Please input an arithmetic expression:"))

The above code explains that eval inside the code above is now not a string, first execute the raw_input () function, Raw_input () returns the evaluation string you entered, and now the Eval function inside is the evaluation string, you can use Eval to evaluate the string. If input: 4*5+6, then Raw_input will return "4*5+6", after Eval evaluates to 26.

Be aware of the difference between the above code and the following code:

print eval(‘raw_input("Please input an arithmetic expression:")‘)

In this code, unlike the Python calculator code, the Eval function is directly a string, then the string is evaluated directly, but the string is a raw_input expression, the Raw_input expression converts the user's input to a string, so if the input 4+5 will return " 4+5 ".  Note: raw_input (' xxxxx ') is an expression in which the value of an expression is user input. What may be confusing is the code: EXEC (' raw_input ("Arithmetic expression:") does not error, because ECEC can also be used for expressions, but nothing is achieved (neither return value nor do anything).

Like exec, Eval can also use namespaces. Because although the expression generally does not reassign the variable, the expression can be used to assign a value to the global variable by calling the function. For example, when the following code is executed, the value of the global variable x is re-assigned to a value of 2:

x=1def inc_x(): global x x=x+1eval("inc_x()")print x

You can see from the code above that the Eval function is also unsafe and that you must use a namespace. In fact, you can provide two namespaces for Eval, one is global and the other is local. The global must be a dictionary, local can be any form of mapping.

EXEC and Eval namespaces use code (namespaces can be not empty dictionaries, you can provide some values for namespaces in advance):

scope={}scope[‘x‘]=1scope[‘y‘]=2print eval(‘x+y‘,scope)

scope={}exec "x=2" in scopeeval("x*x",scope)

Expression methods (that is, exec and Eval methods) that execute a string form of a statement and a string in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.