Thursday, December 26, 2024
Google search engine
HomeLanguageseval in Python

eval in Python

Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program.

Python eval() Function Syntax

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

Parameters:

  • expression: String is parsed and evaluated as a Python expression
  • globals [optional]: Dictionary to specify the available global methods and variables.
  • locals [optional]: Another dictionary to specify the available local methods and variables.

Return: Returns output of the expression.

Uses of Python eval() Function in Python

Python eval() is not much used due to security reasons, as we explored above. Still, it comes in handy in some situations like:

  • You may want to use it to allow users to enter their own “scriptlets”: small expressions (or even small functions), that can be used to customize the behavior of a complex system.
  • eval() is also sometimes used in applications needing to evaluate math expressions. This is much easier than writing an expression parser.

eval() Function in Python Example

Python3




print(eval('1+2'))
print(eval("sum([1, 2, 3, 4])"))


Output:

310

Simple Demonstration of eval() works

Let us explore it with the help of a simple Python program. function_creator is a function that evaluates the mathematical functions created by the user. Let us analyze the code a bit:

  • The above function takes any expression in variable x as input.
  • Then the user has to enter a value of x.
  • Finally, we evaluate the Python expression using the eval() built-in function by passing the expr as an argument.

Python3




def function_creator():
 
    # expression to be evaluated
    expr = input("Enter the function(in terms of x):")
 
    # variable used in expression
    x = int(input("Enter the value of x:"))
 
    # evaluating expression
    y = eval(expr)
 
    # printing evaluated result
    print("y =", y)
 
 
if __name__ == "__main__":
    function_creator()


Output:

Enter the function(in terms of x):x*(x+1)*(x+2)
Enter the value of x:3
y = 60

Evaluating Expressions using Python’s eval()

Evaluate Mathematical Expressions in Python

Evaluating a mathematical expression using the value of the variable x.

Python3




expression = 'x*(x+1)*(x+2)'
print(expression)
 
x = 3
 
result = eval(expression)
print(result)


Output:

x*(x+1)*(x+2)
60

Evaluate Boolean Expressions in Python

Here the eval statement x == 4 will evaluate to False because the value of x is 5, which is not equal to 4. In the second eval statement, x is None will evaluate to True because the value of x is None, and is None checks for object identity, not value equality.

Python3




x = 5
print(eval('x == 4'))
 
x = None
print(eval('x is None'))


Output:

False
True

Evaluate Conditional Expressions in Python

We can also evaluate condition checking on the Python eval() function.

Python3




# check if element in tuple
chars = ('a', 'b', 'c')
print("'d' in chars tuple?", eval("'d' in chars"))
 
# check if number is greater or lesser
num = 100
print(num, "> 50?", eval('num > 50'))
 
# checking if number is even
num = 20
print(num, "is even?", eval('num % 2 == 0'))


Output:

'd' in chars tuple? False
100 > 50? True
20 is even? True

Vulnerability issues with Python eval() Function

Python3




def secret_function():
  return "Secret key is 1234"
 
def solve_expression():
  # expecting input expression
  # containing mathematical operations using x
  expression = input("Enter the function(in terms of x):")
   
  # variable to be used inside expression
  x = input("Enter the value of x:")
   
  # print result of expression evaluated
  print("result:", eval(expression))
   
solve_expression()


Our current version of solve_expression has a few vulnerabilities. The user can easily expose hidden values in the program or call a dangerous function, as eval will execute anything passed to it.

For example, if you input like this:

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

You will get the output:

result: Secret key is 1234

Also, consider the situation when you have imported the os module into your Python program. The os module provides a portable way to use operating system functionalities like reading or writing a file. A single command can delete all files in your system. Of course, in most cases (like desktop programs) the user can’t do any more than they could do by writing their own Python script, but in some applications (like web apps, kiosk computers), this could be a risk!

The solution is to restrict eval to only the functions and variables we want to make available.

Making eval() safe

Python eval function comes with the facility of explicitly passing a list of functions or variables that it can access. We need to pass it as an argument in the form of a dictionary.

Python3




from math import *
 
def secret_function():
    return "Secret key is 1234"
 
def function_creator():
 
    # expression to be evaluated
    expr = input("Enter the function(in terms of x):")
 
    # variable used in expression
    x = int(input("Enter the value of x:"))
 
    # passing variable x in safe dictionary
    safe_dict['x'] = x
 
    # evaluating expression
    y = eval(expr, {}, 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 = {}
    for safe_key in safe_list:
        safe_dict[safe_key] = locals().get(safe_key)
 
    function_creator()


Now if we try to run the above programs like:

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

We get the output:

NameError: name 'secret_function' is not defined

Let us analyze the above code step by step:

  • First, we create a list of methods we want to allow as safe_list.
  • Next, we create a dictionary of safe methods. In this dictionary, keys are the method names and values are their local namespaces.
safe_dict = {}
for safe_key in safe_list:
    safe_dict[safe_key] = locals().get(safe_key)
  • locals() is a built-in method that returns a dictionary that maps all the methods and variables in the local scope with their namespaces.
safe_dict['x'] = x

Here, we add the local variable x to the safe_dict too. No local variable other than x will get identified by the eval function.

  • eval accepts dictionaries of local as well as global variables as arguments. So, in order to ensure that none of the built-in methods is available to eval expression, we pass another dictionary along with safe_dict as well, as shown below:
y = eval(expr, {}, safe_dict)

So, in this way, we have made our eval function safe from any possible hacks!

RELATED ARTICLES

Most Popular

Recent Comments