10
rhein7
7y

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!" 😂

Comments
  • 0
    I don't know python that much, what's wrong ?
  • 1
    @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!
  • 0
    yo@zsixtyfour you can define a set of allowed functions and variables though
  • 0
    Use ast module to do the parsing and do your own evaluation of the tree only allowing math expressions.
  • 2
    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})
  • 0
Add Comment