Python syntax: eval function
usage
eval(expression, globals=None, locals=None)
parameter:
- expression: a required parameter, which can be a string or any code object instance (which can be created by the compile function). If it is a string, it will be analyzed and interpreted as a Python expression.
- globals: Optional parameter, representing the global namespace (storing global variables). If provided, it must be a dictionary object.
- locals: Optional parameter, representing the current local namespace (storing local variables), if provided, any mapping object can be used. If omitted, it will take the same value as globals.
- If both globals and locals are ignored, they will take the global namespace and local namespace under the environment where the eval() function is called.
example
1. Simple expression
print(eval('1+2'))
Output result: 3
2. String to dictionary
print(eval("{'name':'linux','age':18}")
Output result: {'name':'linux','age':18}
3. Pass global variables
print(eval("{'name':'linux','age':age}"{
"age":500}))
Output result: {'name':'linux','age':1822}
4. Transfer local variables (local variables)
age = 20
print(eval("{'name':'linux','age':age}"{
"age":500},locals()))
Output result: {'name':'linux','age':20}