Python eval() Function with Examples

The eval() function is one of the Python built-in functions. The word ‘eval’ can be thought of as a short form for ‘evaluation’, which is the process of finding the output.

In this article, you will be learning about the eval() function, its syntax, properties, and uses with examples. So let us start with the introduction.

Introduction to Python eval() function

The function eval() is a built-in function that takes an expression as an input and returns the result of the expression on evaluation. Let us see the syntax of the eval() function.

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

The first expression is a must, but the next two are default arguments with the default value None. The description of these three parameters is :

1. expression: This is a string that is parsed and evaluated by the interpreter

2. globals: This is a dictionary that contains the global methods and variables

3. locals: This is also a dictionary holding the local methods and variables

This function returns the result on evaluating the input expression.

Let us see some examples of using the eval() function.

Example of eval() function:

eval('3*8')

Output:

24

In this example, the expression is 3*8 which is 24. So, the output is 24.

We can also give sequence and variables as the inputs to this function. For example,

Example of eval() function:

eval('"Python"[0]')

n=5
eval('n==5')

Output:

‘P’

True

In this example, the first eval() has the string with it. Observe that we used double quotes inside the single quotes. The first letter of the string is to be returned, so the output is P. And in the second eval(), the value of the variable ‘n’ is 5. Since 5==5, we get the output as True.

This function can only execute the input string. It cannot compile it. So, when we give a code where the compilation is required we get an error as shown below.

Example of eval() function:

eval('for i in range(5): print(i)')

Output:

Traceback (most recent call last):
File “<pyshell#5>”, line 1, in <module>
eval(‘for i in range(5): print(i)’)
File “<string>”, line 1
for i in range(5): print(i)
^
SyntaxError: invalid syntax

Other Examples of the eval() Function

We can also take the expression as input from the user and then use this for the evaluation. For example,

Example of eval() function with input from the user:

exp=input('Enter an expression: ')

x=int(input('Enter the value of x: '))

eval(exp)

Output:

Enter an expression: x**2+3*x+6

Enter the value of x: 4

34

We can also use the eval function to call a function of choice to do more operations as shown below.

Example of eval() function calling a function:

def add(a,b):
    print(a+b)
def sub(a,b):
    print(a-b)
def prod(a,b):
    print(a*b)
def div(a,b):
    print(a/b)

op=input('Enter either "add" or "sub" or "prod" or "div": ')
if(op in 'add sub prod div'):
    a=input('Enter the first number')
    b=input('Enter the second number')
    fun=op+'('+a+','+b+')'
    eval(fun)
else:
    print('Please enter valid input')

Output:

Enter either “add” or “sub” or “prod” or “div”: div

Enter the first number8

Enter the second number2

4.0

In the above program,

1. First, we take the input of the operation.

2. Then we check if the operation name is in the mentioned operations. This is done by checking if the name exists in the string of all the names.

3. Then we take the input of the two operands

4. After this, we combine the function call strings and store them in the ‘fun; variable.

5. Then we evaluate the fun string.

6. If the operation is not the one in the given options, then we print a message telling us that the wrong input is given.

Python globals and locals parameters

We know that the second and the third parameters of the eval() function are globals and locals. These parameters can be used to restrict the access of the function eval() to certain methods, variables, and objects while evaluating.

Before proceeding further, let us see what global and local objects we have in an empty idle. We can see then using the built-in functions, globals(), locals(), and dir(). For example,

Example of using the globals(), locals() and dir():

globals()

locals()

dir()

Output:

{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>}

{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class ‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’ (built-in)>}

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]

The globals() and the locals() give the dictionary of all the global and local objects respectively. And the dir() gives the list of all the names in the current scope.

We can use the empty dictionary as the global parameter to restrict the eval() to only built-in functions. In this case, even if we import a module, we cannot access the functions from that module. For example,

Example of passing {} as the global parameter:

import math

eval('print("PythonGeeks")',{})

eval('sqrt(4)',{})

Output:

PythonGeeks

Traceback (most recent call last):
File “<pyshell#5>”, line 1, in <module>
eval(‘sqrt(4)’,{})
File “<string>”, line 1, in <module>
NameError: name ‘sqrt’ is not defined

We can see that we could not use the sqrt() function from the math module on using the eval. This is because the second parameter ({}), does not let us use any functions other than the built-in ones. Since print() is a built-in function, we could evaluate it.

We can also restrict it to specific built-in functions. This example is shown below.

Example of restricting eval() to certain built-in functions:

eval('print(abs(-4))',{'__builtins__':{'abs': abs,'print':print}})

Output:

4

In the above example, we are restricting the eval() to only print() and abs() function.

In addition, we can also restrict the eval() to some methods in a module. For example, to restrict to the factorial() function, we can write the below code.

Example of restricting Python eval() to certain functions of a module:

from math import *
print(eval('factorial(5)',{'factorial':factorial}))

Output:

120

We can also pass only the locals by passing the global to None. For example,

Example of restricting eval() to certain functions of a module:

from math import *
n=4
print(eval('sqrt(n)',{'__builtins__': None},{'sqrt':sqrt,'n':n}))

Output:

2.0

In this example, we are giving the sqrt() from the math module and the variable ‘n’ as the locals to the function eval().

Done with learning about the parameters of the eval() function. Let us also see some vulnerabilities of this function in the next section.

Vulnerabilities in Python eval() function

The property of the eval() function to execute anything we pass to is also a problem to us. This is because using this function a user might be able to access confidential data or might call a dangerous function.

1. Issue of exploitation with the eval() function

Assume that we have a function that holds a password. If the user enters an input that calls this function then he/she will be able to view this password. This case is shown in the below code.

Example of the problem of exploitation with the eval():

def get_pass():
    password='python@123'
    return password
exp=input('Enter an expression: ')
eval(exp)

Output:

Enter an expression: get_pass()

‘python@123’

We can see that by just calling a function, the password could be accessed.

Also, take the example of the os module you would like to import on your device. We know that the operating systems provide the option to read-write files. And these constraints are applied to each function

In cases like desktop programs, the user does not have any problem. But consider the case of web applications and kiosk computers, there is a chance of exploitation using this function.

Wondering how to solve this problem? We will discuss this in the next subsection.

2. Solving the problem of exploitation

We can solve this security problem by using safe dictionaries. We can create a safe dictionary containing holding only the x as its value corresponding to the key ‘x’. This dictionary is given as the second parameter of the eval() so that only x will be identified as a global variable while evaluating.

This will prevent the eval() function from accessing the get_pass() function as it does not have this as a global variable to call. And this makes the password or any other confidential data secure.

This example is shown in the below code.

Example of the solving exploitation with the eval():

def get_pass():
    password='python@123'
    return password
exp=input('Enter an expression: ')
x=int(input("Enter the value of x: "))

safe_dic={}
safe_dic['x']=x
eval(exp,safe_dic)

Output:

Enter an expression: x**3+3*x+9
Enter the value of x: 345

We can see that it works good. Now let us try to access the get_pass().

Example of the solving exploitation with the eval():

def get_pass():
    password='python@123'
    return password
exp=input('Enter an expression: ')
x=int(input("Enter the value of x: "))

safe_dic={}
safe_dic['x']=x
eval(exp,safe_dic)

Output:

Enter an expression: get_pass()
Enter the value of x: 4
NameError Traceback (most recent call last)
<ipython-input-10-1080dc81bd37> in <module>
7 safe_dic={}
8 safe_dic[‘x’]=x
—-> 9 eval(exp,safe_dic)<string> in <module>
NameError: name ‘get_pass’ is not defined

We got a NameError because the get_passwords is not in the locals of the eval() function. So, we could prevent the problem of security.

Uses of Python eval() Function

Though this function is rarely used due to its vulnerabilities, it has its applications which include:

1. Allowing the user to give their scriptlets that can be used for customizing the complex systems.

2. Evaluating mathematical expressions more easily compared to writing an expression parser.

Interview Questions on Python Eval() Function

Q1. Write a program to print the result of 4 to the power of 3 using the eval function.
Ans. Below is the example of Python eval():

print(eval('4**3'))

Output:

print(eval(‘4**3’))

Q2. Write a program to take an input of the name of the user and welcome that user.
Ans. Below is the example of eval() with input:

name=input('Enter your name: ')
greet=f'Hello {name}! Welcome to PythonGeeks'
eval('print(greet)')

Output:

name=input(‘Enter your name: ‘)
greet=f’Hello {name}! Welcome to PythonGeeks’
eval(‘print(greet)’)

Q3. Write a program that either appends or removes a value of a list by using the eval() function.
Ans. We can write the two functions, each for append and pop. Then based on the input from the user, we can call the particular function using the eval()

Example of eval() calling functions:

def append(n):
    list1.append(n)
def remove(n):
    list1.remove(n)


list1=[1,2,3,4,5]
cmd=input("Enter either append or remove: ")
num=input('Enter the value to be added or removed: ')

fun=cmd+'('+num+')'
eval(fun)

print(list1)

Output:

Enter either append or remove: remove
Enter the value to be added or removed: 4
[1, 2, 3, 5]

Q4. Write a program to restrict the global methods of the eval() to only print() and the expression.
Ans. Below is the Example of restricting eval() to certain built-in functions:

exp=4+53==7*9
eval('print(exp)',{'__builtins__':{'print':print,'exp':exp}})

Output:

False

Q5. Write a function to restrict the eval() function to access only some local values.
Ans. Below is the example of restricting Python eval() to certailocal variables:

name='xyz'
mail='[email protected]'
pas='123@xyz'

print(eval('name',{'__builtins__': None},{'name':name,'mail':mail}))

print(eval('pas',{'__builtins__': None},{'name':name,'mail':mail}))

Output:

Xyz

TypeError Traceback (most recent call last)
<ipython-input-47-3ed47cabfb60> in <module>
2 mail=’[email protected]
3 pas=’123@xyz’
—-> 4 print(eval(‘pas’,{‘__builtins__’: None},{‘name’:name,’mail’:mail}))
5
6

<string> in <module>

TypeError: ‘NoneType’ object is not subscriptable

Quiz on Python Eval() Function

Conclusion

First, we got introduced to the eval() function and saw some examples. Then we learned about the optional parameters. After this, we saw some of the vulnerabilities related to the eval() and also the solution for this. Finally, we discussed some used and practice questions.

I hope you understood all the concepts of eval() covered in this article. Happy learning!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *