Tip 87 Do Not eval(); It Is Evil

Pythonic Programming — by Dmitry Zinoviev (100 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Assert Conditions | TOC | Parse with literal_eval() 👉

★★2.7, 3.4+ The built-in function eval(expr) is the most misused and dangerous function in the Python standard library. The function takes the string expr and evaluates it as a Python expression. Essentially, eval is a Python interpreter in disguise. You can construct Python expressions on the fly and immediately evaluate them:

​ message = ​'Hello, world!'​
​ command = ​'print(message)'​
​ eval(command)
​ ​# You could have typed the command at the prompt!​
​=> ​Hello, world!​

What could go wrong? Imagine that the command was not produced by your program by a carefully constructed algorithm but was entered by the user. For example, say you develop a program that allows users to calculate arithmetic expressions:

​ command = input(​'Enter the expression you would like to calculate: '​)
​ eval(f​'print({command})'​)
​<= 1+1
​=> ​2​

Seeing how it works, the user becomes somewhat naughty.
!!! DO NOT ATTEMPT TO RUN THIS CODE FRAGMENT !!! THIS FUNCTION WILL DELETE ALL YOUR FILES AND DIRECTORIES !!!

​<= os.system('rm -rf /')
​=> ​0​

The 0 displayed at the command prompt confirms your worst expectations: the user just removed the content of your root directory (or…

--

--

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.