Example of Expression Action of eval Function in Python
- 2021-12-04 19:11:03
- OfStack
What does eval do?
Parses a string expression and executes, returning 1 value
Grammatical format
eval(expression[, globals[, locals]])
expression
: Expression string
globals
: Must be a dictionary
locals
Can be any map object
The simplest expression chestnut
Chestnut 1
print(eval("123"))
print(eval("True"))
print(eval("(1,2,3)"))
print(eval("[1,2,3]"))
# Output result
123
True
(1, 2, 3)
[1, 2, 3]
Chestnut 2
print(eval("1+2"))
x = 1
print(eval('x+1'))
# Output result
3
2
Chestnut 3
a = 1
b = 2
print(eval("[a,b]"))
# Output result
[1, 2]
Take globals with you
# Use globals
x = 10
g = {"x": 5}
print(eval("x+1", g))
# Output result
6
The globals parameters are provided in eval
The scope of eval is the dictionary specified by g. The outside x = 10 is masked, and eval is invisible, so the value of x is 5 is used
x = 10
y = 5
g = {"x": 5}
print(eval("x+1+y", g))
# Output result
5
print(eval("x+1+y", g))
File "<string>", line 1, in <module>
NameError: name 'y' is not defined
An error is reported because the global parameter has no y variable value
Take locals with you
# Use locals
a = 1
g = {"a": 2, "b": 3}
l = {"b": 30, "c": 4}
print(eval("a+b+c", g, l))
# Output result
36
The scope of eval becomes globals + locals
The scope priority of locals will be higher than that of globals
The value in the locals parameter overrides the value in the globals parameter
String-to-dictionary
# String-to-dictionary
jsons = "{'a':123,'b':True}"
print(type(eval(jsons)))
# Output result
<class 'dict'>
Take globals with you
print(eval("{'name':'linux','age':age}", {"age": 123}))
# Output result
{'name': 'linux', 'age': 123}
Take locals with you
print(eval("{'name':'linux','age':age}", {"age": 123}, {"age": 24}))
# Output result
{'name': 'linux', 'age': 24}
Built-in function chestnut
print(eval("123"))
print(eval("True"))
print(eval("(1,2,3)"))
print(eval("[1,2,3]"))
# Output result
123
True
(1, 2, 3)
[1, 2, 3]
0
Chestnuts that report errors
Chestnut 1
print(eval("123"))
print(eval("True"))
print(eval("(1,2,3)"))
print(eval("[1,2,3]"))
# Output result
123
True
(1, 2, 3)
[1, 2, 3]
1
Chestnut 2
print(eval("123"))
print(eval("True"))
print(eval("(1,2,3)"))
print(eval("[1,2,3]"))
# Output result
123
True
(1, 2, 3)
[1, 2, 3]
2
Chestnut 3
print(eval("if x: print(x)"))
# Output result
print(eval("if x: print(x)"))
File "<string>", line 1
if x: print(x)
^
SyntaxError: invalid syntax
Because eval () only accepts expressions, any other statements (such as if, for, while, import, def, class) will throw an error
The above is Python eval function expression usage example details, more about Python eval function expression information please pay attention to other related articles on this site!