Phoenix
Phoenix

Reputation: 4646

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.

Upvotes: 0

Views: 316

Answers (2)

falsetru
falsetru

Reputation: 369134

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

Upvotes: 2

jonrsharpe
jonrsharpe

Reputation: 122062

globals and locals allow you to define the scope in which eval should operate, i.e. 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.

Upvotes: 2

Related Questions