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?
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.