The eval is a built-in function in Python. It is a hack which lets a Python program to run Python code within itself which we ca use in data science.
The eval() function parses the expression which we pass and runs the Python code within the program.
Syntax of eval:
- expression – This is a parse string and we evaluate it as Python code.
- globals(optional) – It is a dictionary that specifies the global methods and variables available.
- locals(optional) – It is also a dictionary, but this specifies the local methods and variables available.
Let us understand it with the use of an example:
function_creator evaluates the mathematical functions which are user creates.
Let us consider an output:
Now we will analyze the code:
- The function above can take any expression in variable X as input.
- Then the user should enter any value of X.
- Then the Python we evaluate the expression using eval() function by passing expr as argument.
Vulnerability issues with eval:
The current version of the function_creator possesses some vulnerabilities. The user is able to expose hidden values in program or call a dangerous function as eval it will execute all things passe to it.
We can import os module in Python program. The module os provides a portable way to use operating system functionalities such as reading or writing a file. We can use a single command to delete all files in the system.
In order to restrict the problems, we should restrict eval to functions and variables we want to make available.
Making eval safe:
The function eval has the facility of explicitly passing a list of functions or variables which we can access. It need to pass in the form of a dictionary.
If the above program is run like:
Now we will analyze the code above:
- First, we create a list of methods which we want to allow as safe_list.
- Then we create a dictionary of safe methods. In the dictionary, keys are method names, and values are local namespaces.
locals() is built-in method that returns a dictionary which maps all method and variables in local scope with their namespaces.
In this local variable, x is added to the safe_dict. In such case, no local variable will get identified other than x, by eval function.
- The eval function accepts dictionaries of local and global variables as arguments. In order to ensure none of the built-in methods is available to eval expression, another dictionary is passed along the safe_dict as shown below:
Uses of eval:
The use of eval is limited due to security reasons. But in certain situations, we need to use it.
- It is also there to allow users to enter their own “scriplets”, small expressions and even small functions that can be there for customizing behavior of complex system.
- It is also there in applications which need to evaluate math expressions. Also, it becomes easier than writing an expression parser.