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.
The following is the function prototype:
eval(expression, globals, locals)
The syntax shown above represents the Python eval()
method and the argument it parses.
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.
The Python eval()
method evaluates a string-based expression by carrying out the following:
Below is an example that uses the eval()
method. It takes in a string and converts it into an integer, float, or complex number.
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)))
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))
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.
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.