Tip 88 Parse with literal_eval()

Pythonic Programming — by Dmitry Zinoviev (101 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Do Not eval(); It Is Evil | TOC | Treat Variables as References 👉

★★★2.7, 3.4+ But what if you want to read a Python data structure, such as a list, dictionary, or set, prepared by str or repr (as explained in Tip 30, Pick to str() or to repr())? And you have been told that eval is not safe (Tip 87, Do Not eval(); It Is Evil)? Should you write your own parser for intrinsic Python data types?

Not so fast! Python actually has a function that, to some extent, is reciprocal to repr. It is called ast.literal_eval and was originally designed to implement custom parsers. As a reminder of those intentions, ast refers to an abstract syntax tree.

Function ast.literal_eval(expr) converts expression expr to a Python object as long as expr is a string representation of bytes, a number, a tuple, a list, a dictionary, a set, a boolean, None, or another string:

​ ast.literal_eval(​'["Mary", None, 23, 3.14, {"pet": "lamb"}]'​)​=> ​['Mary', None, 23, 3.14, {'pet': 'lamb'}]​

The function can evaluate simple arithmetic expressions as long as they do not go beyond addition and subtraction:

​ ast.literal_eval(​'3+3-2'​)​=> ​4​​ ast.literal_eval(​'3+3*2'​)​=> ​Traceback (most recent call last):​
​=> ​ File "<stdin>", line 1…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.