简体   繁体   中英

Python - exec(expression, globals=None, locals=None)

I understand the basic use of eval as shown as an example in the Python standard library:

x = 1
print(eval('x+1'))
2

Could someone please provide a more concise explanation with examples for the utilisation of both the globals and locals arguements.

If you specify global, local namespace, they are used for global, local variables instead of current scope.

>>> x = 1
>>> d = {'x': 9}
>>> exec('x += 1; print(x)', d, d) # x => 9 (not 1)
10

NOTE: x outside the dictionary is not affected.

>>> x
1
>>> d['x']
10

globals and locals allow you to define the scope in which eval should operate, ie which variables should be available to it when attempting to evaluate the expression. For example:

>>> eval("x * 2", {'x': 5, 'y': 6}, {'x': 4})
8

Note that with x in local and global scope, the local version is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM