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 a String parsed as a Python expression and returns its result as an Integer.

  • globals: It represents a Python dictionary that specifies the available global variables and methods. It is an optional parameter.

  • locals: It is similar to the globals parameter 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:

  1. Parsing an expression.
  2. Compilation to bytecode.
  3. Evaluation as a Python expression.
  4. 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 string
sample = 2
evaluate_sample = "10 * 2 / sample"
print(eval(evaluate_sample))
# Printing a string
print_exp = 'print("10 + 17")'
eval(print_exp)
# Another example
evaluate_sample = "10 + 17"
print(eval(evaluate_sample))

Output

10

10 + 17

27

The first print statement returned the result of the expression 102/sample10 * 2 / sample. 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.

Free Resources