All You Need to Know About Eval in Python

Published on Sep 16,2019 2K Views

All You Need to Know About Eval in Python

edureka.co

Everywhere you look around you, you will find an application that has been specifically built to fulfill your needs. Although there are many programming languages that can be used to develop these applications, most of them are built using Python. Python along with its great features and increased versatility brings to the table unique offerings which are both powerful and supremely useful at all times. In this Eval in Python article we will be discussing the following points:

 

What is Eval in Python?

The eval function in Python is one of the most interesting options out there. Some call it a hack and some call it a shortcut, but either way you can make use of it, to run a Python program within a Python code. Pretty cool right?

When you use the eval function, you are basically urging the interpreter to run that is enclosed within the bracket of the eval function.

The syntax for using the eval function in Python is:

eval(expression, globals=None, locals=None)

In the above syntax, 

  1. Expression: It is the string or piece of code that is parsed and evaluated as a Python expression within the Python program itself. 

  2. Globals: It is the dictionary that is used to define all the global methods available to execute the expression mentioned above. This is an optional entity and its uses depend upon your need. 

  3. Locals: Similar to globals, this is another dictionary that is used to specify the available local methods as well as variables. 

To understand the use of this function better, take a look at the example below.

from math import *

def secret_function(): 
	return "Secret key is 1234"

def function_creator(): 

	# expression to be evaluated 
	expr = raw_input("Enter the function(in terms of x):") 

	# variable used in expression 
	x = int(raw_input("Enter the value of x:")) 

	# evaluating expression 
	y = eval(expr) 

	# printing evaluated result 
	print("y = {}".format(y)) 

if __name__ == "__main__": 
	function_creator()

In the above example, function_creator is a function which will evaluate the mathematical expressions created by the user when the program is executed.

Output:

Enter the function(in terms of x):x*(x+1)*(x+2)

Enter the value of x:3

y = 60

Analysis

Now that you have viewed the code shared above, let us analyze it a bit further. 

  1. The above function will take any variable in the expression x as its input. 

  2. Once executed, the user will be prompted to input a value for x, only after which will result for the program be generated.

  3. Finally, the Python program will execute the eval function by parsing the expr as an argument.

 

Drawbacks of Eval

Similar to other built-in functions of Python, eval too comes with a few drawbacks that might create a problem if not accounted. 

If you look at the above example, one of the main vulnerabilities of the function, function_creator is that it can expose any hidden values within the program and also call upon a harmful function as eval by default will execute anything that lies within its parenthesis. 

To understand this further, take a look at the example below.

Input from User

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

Enter the value of x:0

Output:

y = Secret key is 1234

 

Another dangerous situation that comes with using the eval function is to import os module. When you have imported the os module, it allows Python to read and write any files present on your native system without authentication from the user. In such a case, if you mistype a single line of code, all your native files might get deleted. 

The solution to all these drawbacks lies in restricting the capabilities of the eval function.

 

Making Eval Safe in Python

Eval by default comes with the option of parsing any function that it has access to or any which has already been defined. Keeping this in mind while writing your code, will limit the capabilities of eval to a considerable extent thus making sure that you that nothing goes wrong. 

To understand this concept further, take a look at the example below.

from math import *

def secret_function(): 
	return "Secret key is 1234"

def function_creator(): 

	# expression to be evaluated 
	expr = raw_input("Enter the function(in terms of x):") 

	# variable used in expression 
	x = int(raw_input("Enter the value of x:")) 

	# passing variable x in safe dictionary 
	safe_dict['x'] = x 

	# evaluating expression 
	y = eval(expr, {"__builtins__":None}, safe_dict) 

	# printing evaluated result 
	print("y = {}".format(y)) 

if __name__ == "__main__": 

	# list of safe methods 
	safe_list = ['acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 
				'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 
				'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 
				'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 
				'tan', 'tanh'] 

	# creating a dictionary of safe methods 
	safe_dict = dict([(k, locals().get(k, None)) for k in safe_list]) 

	function_creator()

Input from User

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

Enter the value of x:0

Output:

NameError: name 'secret_function' is not defined

As you can see by limiting the access of eval, the chances of a wrong output which can prove to be harmful have been negated.

 

Uses of Eval

As explained in the above sections, due to several security reasons eval is not so commonly used. But still, there are particular use cases where using eval proves to be helpful. Some of the most significant of these are. 

  1. If you want the user to enter their own scriptlets to modify the output of the program, then using the eval function will prove to be helpful. 

  2. While writing expressions to solve mathematical queries you can make use of eval as it is much easier than writing an expression parser.

Now that you know all about eval, we hope you will make use of the same in your day to day programming while keeping in mind the advantages as well as drawbacks.

With this, we come to an end of this Eval in Python article. To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of “Eval in Python” and we will get back to you.

Upcoming Batches For Data Science with Python Certification Course
Course NameDateDetails
Data Science with Python Certification Course

Class Starts on 14th December,2024

14th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES