Dynamic Code Evaluation

Using exec and eval to run Python code from strings

avatar

Sébastien Boisgrault
Associate Professor, ITN Mines Paris – PSL

Python allows dynamic code execution. The function exec allows executing statements:

>>> exec("print('Hello world!')")
Hello world!

And the function eval allows evaluating expressions:

>>> eval("1+1")
2

In many cases, evaluating the string representation of a Python object produces an object identical to the original. For example:

>>> one = 1
>>> repr(one)
'1'
>>> eval(repr(one))
1
>>> eval(repr(one)) == one
True

Or

>>> hello = "Hello world!"
>>> repr(hello)
"'Hello world!'"
>>> eval(repr(hello))
'Hello world!'
>>> eval(repr(hello)) == hello
True

And

>>> numbers = [1, 2, 3]
>>> repr(numbers)
'[1, 2, 3]'
>>> eval(repr(numbers))
[1, 2, 3]
>>> eval(repr(numbers)) == numbers
True

However, this is not a universal rule.

Counterexamples

The representation of a function object does not allow its reconstruction:

>>> def f():
...     pass
... 
>>> repr(f)
'<function f at 0x7f9bd685f640>'
>>> eval(repr(f))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    <function f at 0x7f9bd685f640>
    ^
SyntaxError: invalid syntax

It is possible to find a counterexample using only lists:

>>> loop = []
>>> loop.append(loop)  # Ooooooh! 🤯
>>> repr(loop)
'[[...]]'
>>> ...
Ellipsis
>>> eval(repr(loop))
[[Ellipsis]]
>>> loop2 = eval(repr(loop))
>>> loop2[0] 
[Ellipsis]
>>> loop2[0] == loop2
False
Dangers of eval and exec

The use of eval and exec is often discouraged in practice. In particular, executing unknown code (and thus potentially malicious) can cause major damage; for example, if your Python program, running on your server, executes a string provided by a remote user, and that user provides

code = 'import os\nwhile True:\n\tprint(os.popen(input("$ ")).read())'

Then they have complete access to your server terminal… They can easily add files, read local files and transfer their content over the network, shut down the computer, etc.

The advanced options of exec and eval are detailed in the Python documentation:

  • 📖 exec

  • 📖 eval