Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3, best alternatives to eval()? (input as an expression)

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.

like image 729
Gavin Avatar asked Feb 09 '14 15:02

Gavin


People also ask

What is a safe alternative to using eval ()?

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().

Why you should not use eval Python?

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.

Should I use eval or INT?

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.


2 Answers

Depending on how complicated your expressions are, ast.literal_eval may be a safer alternative.

like image 134
Hugh Bothwell Avatar answered Sep 23 '22 18:09

Hugh Bothwell


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.

like image 40
millimoose Avatar answered Sep 24 '22 18:09

millimoose