Safer than using eval
: you could use a library that will parse mathematical expression - added bonus, you can give a meaningful error message to the user who input it if their input isn't a valid mathematical expression. See Evaluating a mathematical expression in a string - specifically, this answer which gives a hand-rolled parser that can be used like so:
def test2_post():
text = request.form['text']
nsp = NumericStringParser()
nsp.set_variable('x', 10) # you'll have to implement this method
result = nsp.eval(text)
return(result)
The one thing above and beyond the linked answer is providing a way to set a variable. You'd have to extend the code given in that answer - my suggestion would be to keep a dictionary of variables and values inside of the NumericStringParser
object. The set_variable
function sets the value in that dictionary, and you add an alpha-numeric token in the parser that gets converted to the corresponding value in the dictionary of variables and values.
If you haven't worked with writing a parser before, it's a bit out of scope in this question for me to give details - but I'd encourage you to take a few minutes to look into it, it's not as scary as it may seem.
Why bother: if this is for a web app that you're writing, there are very few situations where you could safely eval
user input - it's almost definitely a bad idea. This is a way to execute arbitrary math expressions without the security risk of using eval
.