Python built-in function eval (), exec (), and Complie () functions

Source: Internet
Author: User
Tags define local variable scope

1. Eval function

The eval () function is used to execute a string expression and return the value of the expression.

Eval(expression[, globals[, locals]])      

Parameters
    • Expression--expressions.
    • Globals--variable scope, global namespace, if supplied, must be a Dictionary object.
    • Locals--variable scope, local namespace, if provided, can be any mapping object.
return value

Returns the result of an expression evaluation.

evaluates the value of the specified expression. That is, the Python code that it executes can only be a single expression (note that Eval does not support any form of assignment), not complex code logic. X= 10deffunc (): Y= 20#local variable yA = eval ("X+y")    Print("A:"A#x does not call global variablesb = eval ("X+y",{"x": 1,"y": 2})#define local variables, prioritize calls    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)#for variable d, because the print () function is not a calculation expression, there is no return valueFunc ()

Operation Result:

A:30
B:3
C:4
10 20
D:none

2. EXEC ()

EXEC executes python statements stored in a string or file, and can execute more complex Python code than eval,exec.

EXEC(object[, globals[, locals]])      

Parameters
    • 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: 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.
return value

The exec return value is always None.

the difference between the eval () function and the EXEC () function: the eval () function evaluates only the value of a single expression, and the Exec () function can run code snippets dynamically. The eval () function can have a return value, and the EXEC () function return value is always none. X= 10deffunc (): Y= 20a=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 ()

Operation Result:
A:none   B:nonec:none10 20d:none

example2:x= 10Expr="""z = 30sum = x + y + zprint (sum)"""deffunc (): Y= 20exec(expr)exec(Expr, {'x': 1,'y': 2})    exec(Expr, {'x': 1,'y': 2}, {'y': 3,'Z': 4}) func () Run Result:603334

3. Complie () function

The compile () function compiles a string into a byte code.

Compile(source, filename, mode[, flags[, Dont_inherit]]) 


Parameters
    • Source--A string or an AST (Abstract Syntax Trees) object:
    • FileName-The code file name, which passes some recognizable values if the code is not read from the file.
    • Mode-Specifies the kind of compiled code. can be specified as exec, eval, single.
    • Flags--variable scope, local namespace, if provided, can be any mapping object:
    • Flags and Dont_inherit are used to control when compiling the source code.
return value

Returns the result of an expression execution

>>> str ="3 * 4 + 5">>> a = compile (str,"','Eval')>>>Eval (a)17Compile Beauty/k?m'PA?L/VT. compilation; compiling; editing; [picture] compilations="""#一大段代码for x in range: print (x, end= ") print ()"""code_exec= Compile (S,'<string>','exec')#You must specify mode, specify the wrong and do not specify the error. Code_eval = Compile ('Ten +','<string>','Eval')#an individual expressionCode_single = Compile ('name = input ("Input Your Name:")','<string>',' Single')#Interactivea=exec(code_exec)#the exec is used, so there is no return value, but the print inside the string executesb =eval (code_eval) C=exec(Code_single)#InteractiveD =eval (code_single)Print('A:', a)Print('B:', B)Print('C:', c)Print('Name:', name)Print('D:', D)Print('name;', name)

Operation Result:

Python built-in function eval (), exec (), and Complie () functions

Related Article

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.