Search code examples
pythonpython-3.xeval

Why I cannot use eval(entire_string) straightaway, why do I need to use parser.expr(entire_string).compile()?


Source code for building a calculator using Tkinter

parser.expr(entire_string).compile() VS eval(entire_string)
Version1:

import parser
entire_string = '1+2'
a = parser.expr(entire_string).compile()
result = eval(a)

Version2:

entire_string = '1+2'
result = eval(entire_string)

What is the point of using parser.expr(entire_string).compile() , why not use eval(entire_string) straight away?


Solution

  • This is because eval in python is dangerous. If the string is input by the user, then they can execute arbitrary code on your machine. This is particularly dangerous if it's running on a remote server.

    The parser will parse just an expression and return a value without allowing arbitrary python code to run.