Eval (source[, globals[, locals])
Role:
Evaluates the string str as a valid expression and returns the result of the calculation. Parameter: Source: The code object returned by a Python expression or function compile (); Globals: Optional. Must be dictionary;locals: Optional. Any map object.
Instance:
1 #################################################2 string conversion to list3>>>a ="[ [up], [3,4], [5,6], [7,8], [9,0]]"4>>>type (a)5<type'Str'>6>>> B =Eval (a)7>>>Printb8[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]9>>>type (b)Ten<type'List'> One ################################################# A convert strings into dictionaries ->>> A ="{1: ' A ', 2: ' B '}" ->>>type (a) the<type'Str'> ->>> B =Eval (a) ->>>Printb -{1:'a', 2:'b'} +>>>type (b) -<type'Dict'> + ################################################# A string Conversion Narimoto Group at>>> A ="([up], [3,4], [5,6], [7,8], (9,0))" ->>>type (a) -<type'Str'> ->>> B =Eval (a) ->>>Printb -([1, 2], [3, 4], [5, 6], [7, 8], (9, 0)) in>>>type (b) -<type'tuple'>
1 #Test eval () and locals ()2x = 13y = 14NUM1 = eval ("X+y")5 Print(NUM1)6 7 defg ():8x = 29y = 2Tennum3 = eval ("X+y") One Print(num3) Anum2 = eval ("X+y", Globals ()) - #num2 = eval ("X+y", Globals (), locals ()) - Print(num2) the - g () - - PrintLocals () ["x"] + PrintLocals () ["y"] - PrintGlobals () ["x"] + PrintGlobals () ["y"]
The value of NUM1 is the value of 2;NUM3 is also well understood, is the value of 4;num2? Given the globals () parameter, you should first find the global x and Y values, which are all 1, so it is clear that the num2 value is also 2. If you comment out the sentence, do the following sentence? According to the 3rd point, the result is 4.
eval () Use reason:
1) in the compilation language to generate code dynamically, is basically impossible, but dynamic language is possible, meaning that the software has been deployed to the server, but as long as a few changes, have to directly modify this part of the code, you can immediately realize the change without the entire software reload.
2) in Machin learning based on the user's use of the software frequency, as well as the way, can dynamically modify the code to adapt to user changes.
Note:
Eval has security issues, such as the user's malicious input will get the current directory file
1 eval ("__import__ (' OS '). System (' dir ')")
1 Import OS 2 ' OS ' inch Globals () 3 True 4 >>> os.system ('whoami')5 Ap\zhail
How to avoid security problems?
1, self-written check function;
2. Using Ast.literal_eval
Python function-eval ()