Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there ever a good reason to use eval()?

Tags:

It seems to me that eval() is treated with the same disdain that goto is. And by eval, I mean a function for executing a string as code, as seen in PHP, Python, JavaScript, etc. Is there ever a situation where using eval() is justified (except perl)? And if not, why do so many languages implement it?

like image 690
GSto Avatar asked Dec 01 '09 15:12

GSto


People also ask

Should you ever use eval?

Any code that is evil in EVAL, is evil in the browser itself. The attacker or anyone can easily inject a script node in DOM and do anything if he/she can eval anything. Not using EVAL will not make any difference. It is mostly poor server-side security that is harmful.

When should you use eval?

Eval function is mostly used in situations or applications which need to evaluate mathematical expressions. Also if the user wants to evaluate the string into code then can use eval function, because eval function evaluates the string expression and returns the integer as a result.

Is it OK to use eval in Python?

Python eval() function is very powerful. Even though we have globals and locals variable to restrict access, they are not enough and workaround are available to harm your system. Read this article explaining why eval is dangerous. You shouldn't use eval() function with untrusted user inputs.


1 Answers

Yes - when there is no other way to accomplish the given task with a reasonable level of clarity and within a reasonable number of lines of code.

This eliminates 99% of cases where eval is used, across the board in all languages and contexts.

like image 148
yfeldblum Avatar answered Jan 02 '23 00:01

yfeldblum