exec, eval and complie in python

1.eval function

What the function does:

Calculates the value of the specified expression . That is to say, the python code to be executed can only be a single expression (note that eval does not support any form of assignment operation), not complex code logic.

eval(source, globals=None, locals=None, /)

Parameter Description:

source: a required parameter, which can be a string or an arbitrary code (code) object instance (can be created by the complie function). If it is a string, it is parsed and interpreted as a python expression (using the globals and locals parameters for the global and local namespaces).

globals: optional parameter, representing the global namespace (store global variables), if provided, it must be a dictionary object.

locals: optional parameter, representing the global namespace (store local variables), if provided, can be any mapping object. If the parameter is omitted, it will take the same value as globals.

If both globals and locals are omitted, they will take the global namespace and local namespace of the environment in which the eval() function is called.

return value:

If the source is a code object, and when creating the code object, the mode parameter of the complie function is 'exec', then the return value of the eval() function is None;

Otherwise, if source is an output statement, such as print(), eval() returns None;

Otherwise, the result of the source expression is the return value of the eval() function

Example:

 

x = 10
def func():
    y = 20   #局部变量y
    a = eval("x+y")
    print("a:",a)      #x没有就调用全局变量
    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("print(x,y)")
    print("d:",d)   #对于变量d,因为print()函数不是一个计算表达式,因此没有返回值
func()

Output result:

a: 30
b: 3
c: 4
10 20
d: None

 

2. exec function

What the function does:

Execute python code dynamically . That is to say, exec can execute complex python code, unlike the eval function, which can only calculate the value of an expression.

exec(source, globals=None, locals=None, /)

source: a required parameter, indicating the python code that needs to be specified. It must be a string or a code object. If source is a string, the string will be parsed into a set of python statements and then executed. If source is a code object, then it is simply executed.

return value:

The return value of the exec function is always None.

 

The difference between eval() function and exec() function:

The eval() function can only calculate the value of a single expression, while the exec() function can run code segments dynamically.

The eval() function can have a return value, while the return value of the exec() function is always None.

Example 1:

Let's take the example in eval and execute it

 

x = 10
def func():
    y = 20
    a = exec("x+y")
    print("a:",a)
    b = exec("x+y",{"x":1,"y":2})
    print("b:",b)
    c = exec("x+y",{"x":1,"y":2},{"y":3,"z":4})
    print("c:",c)
    d = exec("print(x,y)")
    print("d:",d)
func()

 

Results of the:

 

#exec不会有任何返回值
a: None   
b: None
c: None
10 20
d: None

 

Example 2

x = 10
expr = """
z = 30
sum = x + y + z   #一大包代码
print(sum)
"""
def func():
    y = 20
    exec(expr)   10+20+30
    exec(expr,{'x':1,'y':2}) 30+1+2
    exec(expr,{'x':1,'y':2},{'y':3,'z':4}) #30+1+3,x是定义全局变量1,y是局部变量

func()

Results of the:

60
33
34

 

3.complie function

What the function does:

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Parameter description :

source: string or AST object, representing the python code that needs to be compiled

filename: Specify the code file that needs to be compiled, if it is not a file to read the code, pass some identifiable value.

mode: used to identify the type of representative that must be compiled; if the source is composed of a sequence of code statements, specify mode='exec'; if the source is composed of a single expression, specify mode='eval'; if the source is Consists of a single interactive statement, specify modo='single'. It must be formulated, otherwise an error will be reported.

example:

s = """              #一大段代码
for x in range(10):
    print(x, end='')  
print()
"""
code_exec = compile(s, '<string>', 'exec')   #必须要指定mode,指定错了和不指定就会报错。
code_eval = compile('10 + 20', '<string>', 'eval')   #单个表达式
code_single = compile('name = input("Input Your Name: ")', '<string>', 'single')   #交互式

a = exec(code_exec)   使用的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)

 

Results of the:

 

0123456789  #有print就会打印
Input Your Name: kebi
Input Your Name: kebi
a:  None
b:  30
c:  None
name:  kebi
d:  None
name;  kebi

 

Guess you like

Origin blog.csdn.net/qq_17758883/article/details/104653509