What is the eval() method in Python?
Python contains many built-in methods that make it a convenient and accessible language. The eval() method is one such method. It parses and evaluates an expression as an argument.
Syntax
The following is the function prototype:
eval(expression, globals, locals)
The syntax shown above represents the Python eval() method and the argument it parses.
Parameters
It takes three parameters which are described below.
-
expression: It evaluates aStringparsed as a Python expression and returns its result as anInteger. -
globals: It represents a Python dictionary that specifies the available global variables and methods. It is an optional parameter. -
locals: It is similar to theglobalsparameter described above but it specifies the available local methods and variables. It is also an optional parameter.
Evaluating an expression
The Python eval() method evaluates a string-based expression by carrying out the following:
- Parsing an expression.
- Compilation to bytecode.
- Evaluation as a Python expression.
- Returning the evaluated expression as a result.
Below is an example that uses the eval() method. It takes in a string and converts it into an integer, float, or complex number.
Code
number = "50"print(eval(number), type(eval(number)))float_number = "50.33"print(eval(float_number), type(eval(float_number)))complex_number = "1+2j"print(eval(complex_number), type(eval(complex_number)))
Output
50
50.33
(1+2j)
The eval() function in the example above was able to identify the expressions in the string and convert them to their respective types. Note that if characters and alphabets are parsed as an expression, it would return an error. Another example is shown below.
# Solving mathematical expression with variable name inside the stringsample = 2evaluate_sample = "10 * 2 / sample"print(eval(evaluate_sample))# Printing a stringprint_exp = 'print("10 + 17")'eval(print_exp)# Another exampleevaluate_sample = "10 + 17"print(eval(evaluate_sample))
Output
10
10 + 17
27
The first print statement returned the result of the expression . The second print statement returned the expression in the string while the third print statement returned the sum of the expression in the string.
Conclusion
The eval() method is not considered secure because it allows the users to execute arbitrary Python code.
However, it is useful when you want to operate Python expressions without the hassle of creating your own expressions evaluator from scratch.