89DEVs

Python eval() function

eval() overview

The eval() function parses and evaluates string-based input and compiled code. Before using the eval() function some security vulnerabilities should be considered: For example if user input is passed to the eval() function: eval(input()). This would allow users to run malicious code on the server. To resolve this vulnerability, it is necessary to restrict available methods and variables for user input.

eval() on string-based input

In this example we pass some string based input to the eval() function. The expressions we pass to eval() perform some basic arithmetic operations. # eval() on string-based input eval("2 * 2") eval("5 + 5") eval("sum([1, 2, 3, 4, 5])") The eval() function parses the expressions and evaluates them. The results are returned. 4 10 15

eval() using compiled code

The second option, next to string-based input, is to use the eval() function with compiled code. The code is compiled using the compile() function. It returns a code object of the compiled code, which can be passed to the eval() function. # eval() using compiled code myString = 'my favorite number is ' myNumber = 777 # myCode expression myCode = myString + str(myNumber) # compile the code compiledCode = compile('myCode', 'null', 'single') # evaluate the code eval(compiledCode) The expression myCode combines the string and the number as a string. Then compile() is used to compile the code. And finally eval() evaluates the compiled code. The result of the expression is returned. 'my favorite number is 777' Like demonstrated on the compile() function page, it is possible to compile code from a file.

eval() Syntax

The syntax of the eval() function is: eval(expression, globals=None, locals=None)

eval() arguments

The eval() function accepts between 1 and 3 arguments. The first argument is the expression and required. The following two arguments are globals and locals and are optional.
  • required: expression, the expression to be evaluated by Python
  • optional: globals, the global variables passed as dictionary
  • optional: locals, the local variables passed as dictionary
  • eval() return values

    The eval() function returns the result of the evaluated expression.

    related functions

    The related functions of eval() are the exec() and compile() function: The exec() function allows to execute code block instead of single expressions. The compile() function allows to compile code, to be evaluated by eval().

                
        

Summary


Click to jump to section