Evaluating a string containing a Python literal with ast.literal eval

suggest change

If you have a string that contains Python literals, such as strings, floats etc, you can use ast.literal_eval to evaluate its value instead of eval. This has the added feature of allowing only certain syntax.

>>> import ast
>>> code = """(1, 2, {'foo': 'bar'})"""
>>> object = ast.literal_eval(code)
>>> object
(1, 2, {'foo': 'bar'})
>>> type(object)
<class 'tuple'>

However, this is not secure for execution of code provided by untrusted user, and it is trivial to crash an interpreter with carefully crafted input

>>> import ast
>>> ast.literal_eval('()' * 1000000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RecursionError: Stack overflow (used 2912 kB) during compilation

Here, the input is a string of () repeated one million times. Current CPython raises RecursionError while compiling it. The segmentation fault in older transcripts did not occur here. The kilobyte figure in that message can differ. Parser and tokenizer failures are still possible, and this is not a security boundary.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents