AppDividend
Latest Code Tutorials

Python Eval Function Tutorial With Example

0

Python Eval Function Tutorial With Example is today’s topic.  The eval() method parses the expression passed to that function it and runs python expression(code) within the program. In simple terms, Python eval() method runs the python code, which is passed as an argument within the program. The eval() method returns the result evaluated from the expression.

Python Eval Function Tutorial

The syntax of eval() method is following.

eval(expression, globals=None, locals=None)
  1. expression – this string is parsed and evaluated as Python expression.
  2. globals (optional) – a dictionary.
  3. locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python.

See the following example of eval() function in Python.

# app.py

k = 21
print(eval('k + 1'))

So, in the above code, k + 1 evaluates as a 21 + 1 and we get an output 22.

 

Python Eval Function Tutorial

So, eval function takes an expression and execute that expression and gives the output.

Let’s take a real-time example of eval function.

# app.py

def square(l):
  return l*l

def cube(l):
  return l*l*l

param = input('Type a function: ')

for l in range(1, 5):
    if (param == 'square(l)'):
        print('The square of l is:', eval(param))
    elif (param == 'cube(l)'):
	    print('The cube of l is:', eval(param))
    else:
        print('You have entered the wrong function')
        break

Above code has two choices of functions.

  1. Square
  2. Cube

If the user types the square(l), then it will return the squares of the values in for loop and if cube it will create the cubes of each value from 1 to 5. See the below output.

 

Python Eval Function Tutorial With Example

If you are using an eval(input()) in your code, it’s an excellent idea to check which variables and methods a user can use. You can see which variables and functions are available using the Python dir() function.

More often than not, all the available functions and variables used in the expression (first parameter to the eval()) may not be needed, or even may have the security loop hole. You may need to restrict the use of these methods and variables for eval() method. You can do so by passing optional globals and locals parameters (dictionaries) to the eval() function.

If both parameters are omitted (as in our earlier examples), the expression is executed in the current scope. You can check the available variables and methods using the following code.

print(eval('dir()'))

Passing globals parameter; locals parameter is omitted

The globals and locals parameters (dictionaries) are used for global and local variables respectively. If the locals dictionary is omitted, it defaults to the globals dictionary. Meaning, globals will be used for both global and local variables. See the following example.

from math import *
print(eval('dir()', {}))

The output of the eval function is following.

 

Passing globals parameter; locals parameter is omitted

If you pass the empty dictionary as globals, only the __builtins__ are available to expression (first parameter to the eval()). Even though we have imported the math module in an above program, expression can’t access any of the functions provided by the math module.

Making Certain Methods available

Write the following code inside the app.py file in order to make certain methods available to the user.

from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))

See the below output.

 

Making Certain Methods available

Here, the expression can also use the sqrt() and pow() methods along with __builtins__.

Also, it’s possible to change the name of the method available for the expression according to your wish.

Passing both globals and locals dictionary

You can make needed functions and variables available for the use by passing locals dictionary. See the following example.

# app.py

from math import *

k = 4
print(eval('sqrt(k)', {'__builtins__': None}, {'k': k, 'sqrt': sqrt}))

See the following output.

 

Passing both globals and locals dictionary

Finally, Python Eval Function Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.