Why Is Using ‘eval’ A Bad Practice?

Why is using eval a bad practice?

Are you using the eval function to evaluate the mathematical expression in Python? Yes, many of you might be. But do you even know that using eval can be a bad practice?  Now, if you are wondering why? Then probably you should stick around and understand this, with a couple of good examples, and get a solution for it.

Why is using ‘eval’ a bad practice? 

It has been seen that the eval function starts deleting the system files and corrupts the system’s environment. Therefore, whenever you use the eval() function for executing the user input code, be careful.

Moreover, make sure that you must check the user-entered data first, and when it looks fine only then go for it.

Well, this blog will help you to find out the other reasons why eval can be a bad practice. Moreover, we have tried to detail the alternative functions that you can use at the place of eval.

Do not worry. We have mentioned relevant examples with the details so that it will be more easy for you to understand the eval() function.

Now that we understand why is using eval a bad practice, let’s find out the essential details about the eval function.

First, let’s take an overview of the eval function in Python!

What is an eval function in Python?

eval is one of the built-in functions in Python. It parses the given argument and evaluates the expressions. 

Or simply, I can say that the eval function in Python evaluates the “stringas the expression and returns the output result as the “integer“.

Key point:
The eval function of Python takes the string as “argument,” and evaluates it as the Python “expression.” The result of the Python expression is an “object.”

The basic syntax of the eval function is:

expression: The string that is evaluated as the Python expression.globals (optional): The dictionary that specifies the global variables and methods.locals (optional): The dictionary that specifies the local variables and methods.

What is the basic use of the eval function?

This function uses when there is a requirement to evaluate mathematical expressions. Moreover, Python users use it to evaluate the string into codes.

It is possible just because the eval function is evaluating the string expressions and returning the result in the form of an integer.

Now, let’s take an example of how to use the eval function in Python!

Input

‘x**2’

‘3’

Output:

Enter the equation(in terms of x):x**2

<type ‘str’>

Enter the value of x:3

y = 9

<type ‘int’>

NOTE: function_creator is one of those functions that evaluate the user-created mathematical functions.

Moreover, you can see that the input is given as the string, and the output of the eval function is in integer form.

Now, let’s find out the reason why and how ‘eval” can be a bad practice!!

In the above code, you can see that there is a function_creator that has few limitations. Like the user can call the function to get the hidden value of the program. This will happen because the eval just executes whatever is passing to it.

It will look like this:

Input:

‘secret_function()’

‘0’

Output:

Enter the equation(in terms of x):secret_function()

Enter the value of x:0

y = Secret key is 159

This issue can also occur if you import the OS module in any of the Python programs. The portable way of OS allows us to utilize OS functionalities, such as write or read a file. 

It is quite dangerous to use as its single command can delete almost all the system files!!

Now, you might be thinking why do I use it then? Well, while writing the Python script for some applications like kiosk computers, web apps, and more, you need to take a risk to use it.

Sum up: eval can also be a bad practice because of the following reasons:
It is insecure and very dangerous. It is quite slow. Makes the process of debugging quite difficult.

Then, why do Python users still use the eval function?

Well, eval is not much in use as you might be thinking just because of security reasons.

But in some situation, you may need to use it, like:

  • When you allow other users to enter their “scriptlets,” which use to customize the complex system’s behavior.
  • The eval function is practiced to evaluate mathematical expressions.

Is there any way to make eval safe or use any other function instead?

Yes, there is!!

Python users can pass the list of variables and functions as arguments to a dictionary.

How?

Let’s check it in the below code:

Input: 

‘x**2’

‘3’

Output:

Enter the equation(in terms of x):x**2

<type ‘str’>

Enter the value of x:3

y = 9

<type ‘int’>

Now, when you enter the input as secret_function() and the value of x as 0, then the output will be different from the previous case.

Input:

‘secret_function()’

‘0’

Output:

Enter the equation(in terms of x):secret_function()

<type ‘str’>

Enter the value of x:0

NameError: name ‘secret_function’ is not defined

Now, let’s understand what is happening here.

First, we have created a safe dictionary method where “keys” are the names and their namespace is “values”.

safe_dict = dict([(k, locals().get(k, None)) for k in safe_list])

Here, locals() returns the dictionary that uses to map the variables and methods in the local scope along with the namespaces.

safe_dict[‘x’] = x

Keep in mind that you need to add x to the safe_dict so that other variables other than x need to be identified by the eval function.

y = eval(expr, {“__builtins__”:None}, safe_dict)

Now, eval takes global and local variables’ dictionaries as arguments. To ensure that there is no built-in method available, we have passed other dictionaries from the safe_dict function as well.

This is how you can easily make the eval safe to use.

Conclusion

So, we hope we are able to coil up multiple reasons and probable solutions to the obvious question that we started with- Why is using eval a bad practice? With relevant examples, we have seen that using eval can be a bad practice, but still it is in use. However, if possible, try to use the dict function instead of the eval function. On the other hand, if there is an unavoidable requirement of using eval, then do not hesitate to use it.

If you have any query regarding the use of the eval function or anything related to the eval, comment it in the below section. I will help you with solving your Python-related queries in the best possible way.

“Master Python with ease, with GUVI .”

Test what you have learned from this blog!!!

  1. Is the statement correct or incorrect?

“Eval can accept the expressions, an error will arise if you use if, while, def, class, for with eval.”

(A) Correct

(B) Incorrect

Correct Answer: (A) it is correct that eval can only accept the expression. 

  1. Is the statement correct or incorrect?

“If I remove all the builtins and the global, then eval will become safe to use.”

(A) Correct

(B) Incorrect

Correct Answer: (B) it is incorrect because after removing builtins and globals, eval is still a bad practice.

  1. If you have the string input that matches with the dictionary object. Which function would be better to use?

(A) Generator expression

(B) Eval

(C) Both (A) and (B)

(D) None of above

Correct Answer: (B) Because generator expression can be used when you have string input but it does not match with the dictionary objects. Therefore, the eval function can be used instead.

  1. What will be the output of this code:

x = 3**2

print(eval(‘x + 1’))

(A) 4

(B) 6

(C) 7

(D) 10

Correct Answer: (D) first, x has the value of the square of 3 that is 9, then eval will evaluate the math operation that is 9+1 =>10 and give output as 10.

  1. What will be the output of the following code:

x = 5

y = 2

print(eval(‘x + y’))

(A) 7

(B) 10

(C) 3

(D) Error

Correct Answer: (A) as the eval is evaluating the “addition” mathematical operation. Therefore x + y = 5 + 2 => 7.

Archana

A traveler, and explorer, Archana is an active writer at GUVI. You can usually find her with a book/kindle binge-reading (with an affinity to the mystery/humor).

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x