I'm using Python 3.
I suppose the best way to ask this is how can I input an expression without using eval(input("Input: "))
?
I'm a simple user right now, so what I needed eval for was an algebra calculator.
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().
Since the eval() function will evaluate any Python expressions, the hacker can easily get a list of files and folders on the server. To be honest, you probably will be fired if the above string is really evaluated by the eval() function.
Advice: use int , because it's safer, doesn't have security issues (eval can evaluate any expression, including system calls and file deletion), and suits your purpose perfectly.
Depending on how complicated your expressions are, ast.literal_eval
may be a safer alternative.
If you're the only person using that app and thus don't need to be worried about security issues, just keep using eval()
or exec()
.
Otherwise, just use a safe library for the specific task you need. E.g. numexpr I guess for a calculator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With