Content of this article
1. Eval () function Introduction
2. Eval () application
I. Introduction to the eval () function
Eval (source[, globals[, locals])
Function: evaluates the string str as a valid expression and returns the result of the calculation
Parameters:
Source: The code object returned by a Python expression or function compile ()
Globals: Optional. It must be dictionary.
Locals: Optional. Arbitrary map Object
Second, eval () application
Do not pass in incoming globals, locals
data1 = ‘1‘ret1 = eval(data1)print(ret1, type(ret1)) # 1 <class ‘int‘>data2 = ‘[1,2,3,4]‘ret2 = eval(data2)print(ret2, type(ret2)) # [1, 2, 3, 4] <class ‘list‘>data3 = ‘(1,2 ,3,4)‘ret3 = eval(data3)print(ret3, type(ret3)) # (1, 2, 3, 4) <class ‘tuple‘>data4 = ‘{"name":"allen", "age":15}‘ret4 = eval(data4)print(ret4, type(ret4)) # {‘name‘: ‘allen‘, ‘age‘: 15} <class ‘dict‘>data5 = ‘{1,2,3,4}‘ret5 = eval(data5)print(ret5, type(ret5)) # {1, 2, 3, 4} <class ‘set‘>ret6 = eval(‘1+1‘)print(ret6, type(ret6)) # 2 <class ‘int‘>
Incoming Globals, locals
x = 2y = 2num2 = eval("x+y")print(num2) # 4num3 = eval("x+y", globals()) print(num3) # 2num4 = eval("x+y",globals(),locals()) print(num4) # 4
Python eval () function