0

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.

Phoenix
  • 4,386
  • 10
  • 40
  • 55
  • amended question, good spot. – Phoenix Feb 19 '14 at 15:10
  • 1
    In general, do not use either `exec` or `eval` unless you absolutely know what you're doing and are certain that using it is the best possible way to solve your problem. `exec` and `eval` should usually be avoided at all costs because they introduce a multitude of problems: They're nigh-unsolvable security hazards when used on user input, can slow your code down considerably (as `exec` can manipulate locals, it actively turns off optimizations for local variables in the scope where it's used), introduce hard to find bugs, are a hassle to refactor, reduce readability, etc, etc, etc... – l4mpi Feb 19 '14 at 15:16

2 Answers2

2

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437