Python Language Dynamic code execution with `exec` and `eval` Evaluating an expression with eval using custom globals


>>> variables = {'a': 6, 'b': 7}
>>> eval('a * b', globals=variables)

As a plus, with this the code cannot accidentally refer to the names defined outside:

>>> eval('variables')
{'a': 6, 'b': 7}
>>> eval('variables', globals=variables)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'variables' is not defined

Using defaultdict allows for example having undefined variables set to zero:

>>> from collections import defaultdict
>>> variables = defaultdict(int, {'a': 42})
>>> eval('a * c', globals=variables)  # note that 'c' is not explicitly defined