Tutorial Study Image

Python eval()

The eval() function executes the expression given as its argument. The expression is evaluated and parsed as a valid python statement. The expression always a string and it is mandatory for the eval() function.

eval(expression, globals=None, locals=None) #Where expression can be a string to evalate

eval() Parameters:

Takes 3 parameters where the first parameter is mandatory and the other two are optional.

Parameter Description Required / Optional
expression This parameter is a string, and it is parsed and executed as a python expression Required
globals  It is a dictionary. And it is used to specify the expressions available for execution. Optional
locals It specifies the local variables and methods in the eval() Optional

eval() Return Value

Input Return Value
Expression result of the expression
Both globals and locals omitted expression is executed in the current scope
globals exist; locals are omitted globals will be used for both global and local variables
both globals and locals exist result as per the parameter

Examples of eval() method in Python

Example 1: Demonstrate use of eval()

# Perimeter of Square
def calculatePerimeter(l):
    return 4 * l

# Area of Square
def calculateArea(l):
    return l * l

exp = input("Type a function: ")

for l in range(1, 5):
    if exp == "calculatePerimeter(l)":
        print("If length is ", l, ", Perimeter = ", eval(exp))
    elif exp == "calculateArea(l)":
        print("If length is ", l, ", Area = ", eval(exp))
        print("Wrong Function")


Type a function: calculateArea(l)
If length is  1 , Area =  1
If length is  2 , Area =  4
If length is  3 , Area =  9
If length is  4 , Area =  16

Example 2:Working of eval() when both globals and locals parameters omitted.

from math import *


['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'os', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

Example 3:Passing empty dictionary as globals parameter

from math import *
print(eval('dir()', {}))

# The code will raise an exception
print(eval('sqrt(25)', {}))


Traceback (most recent call last):
  File "", line 5, in 
    print(eval('sqrt(25)', {}))
  File "", line 1, in 
NameError: name 'sqrt' is not defined

Example 4:Making Certain Methods available

from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))


['__builtins__', 'pow', 'sqrt']

Example 5: Passing both globals and locals dictionary

from math import *

a = 169
print(eval('sqrt(a)', {'__builtins__': None}, {'a': a, 'sqrt': sqrt}))