Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
@Orionss "eval" is a function in most interpreted langs that can execute arbitrary code on runtime from a string.
Very helpful for development, however has no place in shipped software as a user could do *anything*. Like sql injection, but worse! -
login1057yUse ast module to do the parsing and do your own evaluation of the tree only allowing math expressions.
-
The 2nd and third parameter to eval is the global and local scope (by default it uses the current scope) , if you call: eval(userprovidedstring,
{"__builtins__":None},{}) it is perfectly safe. (you need to set __builtins__ to None in the global scope dictionary to remove access to built in functions like open, exec, __import__ etc).
If you want to allow the user to call a limited set of safe functions (i.e, some math functions) you can put those in the local dictionary: i.e:
eval(userstring, {"__builtins__": None}, {"sqrt": math.sqrt, "sin": math.sin, "cos": math.cos, etc})
Related Rants
A friend of mine (beginner) wrote a Python script that calculated the derivative function of an function the user typed in. He showed it to me and
I said: "You should not use eval()!"
He: "Oh, ok. May you write a parser?"
I: "Wait! It's ok. Just use eval!" 😂
undefined
eval is evil