eval method in Python?

PythonServer Side ProgrammingProgramming

Python eval() method is used to parse an expression string as python expression and then runs python expression within the program.

Syntax

The general python eval() method syntax is,

eval(expression, globals=None, locals=None)

where:

  • expression: required string parameter, this is the expression string being parsed and executed as python expression.

  • globals: Optional parameter is a dictionary used to specify the expressions available to execute. If not explicitly mentioned, standard built-in methods are available like ‘__builtins__’: None element.

  • locals: Optional parameter, used to specify the local variables and methods available to eval() function.

Now to better understand the eval() method, lets understand it through different examples.

Simple eval() method

str1 = 'Hello'
print(eval('str1 =="Hello"'))
print(eval('str1 + ", Python"'))

Output

True
Hello, Python

Python eval() method with user input

from math import *
for l in range(1,3):
   func = input("Enter Math Function to Evaluate:\n")
   try:
      print(eval(func))
      except Exception as ex:
      print(ex)
      break
print('Done')

Output

Enter Math Function to Evaluate:
abs(-42)
42
Enter Math Function to Evaluate:
max(12, 3, 4 , 2, 17)
17
Done

Python eval() globals and locals

Before understanding what functions we need to pass to eval() methods, let’s get list of all functions and variables are present in the global and local scope.

from math import *
def square_root(n):
   return sqrt(n)
# Print current global symbol table as a dictionary
print('List of Global symbols:\n',globals())
#Print current local symbol table as a dictionary
print('\nList of Local symbols:\n',locals())
#print list of names in the current local scope
print('\nList of names in current local scope:\n',dir())

Output

List of Global symbols:
{'__name__': '__main__',
'__doc__': None,
'__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'__file__': 'C:/Python/Python361/eval_example1.py',
'acos': <built-in function acos>,
'acosh': <built-in function acosh>,
'asin': <built-in function asin>,
'asinh': <built-in function asinh>,
'atan': <built-in function atan>,
'atan2': <built-in function atan2>,
'atanh': <built-in function atanh>,
'ceil': <built-in function ceil>,
'copysign': <built-in function copysign>,
'cos': <built-in function cos>,
'cosh': <built-in function cosh>,
'degrees': <built-in function degrees>,
'erf': <built-in function erf>,
'erfc': <built-in function erfc>,
'exp': <built-in function exp>,
'expm1': <built-in function expm1>,
'fabs': <built-in function fabs>,
'factorial': <built-in function factorial>,
'floor': <built-in function floor>,
'fmod': <built-in function fmod>,
'frexp': <built-in function frexp>,
'fsum': <built-in function fsum>,
'gamma': <built-in function gamma>,
'gcd': <built-in function gcd>,
'hypot': <built-in function hypot>,
'isclose': <built-in function isclose>,
'isfinite': <built-in function isfinite>,
'isinf': <built-in function isinf>,
'isnan': <built-in function isnan>,
'ldexp': <built-in function ldexp>,
'lgamma': <built-in function lgamma>,
'log': <built-in function log>,
'log1p': <built-in function log1p>,
'log10': <built-in function log10>,
'log2': <built-in function log2>,
'modf': <built-in function modf>,
'pow': <built-in function pow>,
'radians': <built-in function radians>,
'sin': <built-in function sin>,
'sinh': <built-in function sinh>,
'sqrt': <built-in function sqrt>,
'tan': <built-in function tan>,
'tanh': <built-in function tanh>,
'trunc': <built-in function trunc>,
'pi': 3.141592653589793,
'e': 2.718281828459045,
'tau': 6.283185307179586,
'inf': inf,
'nan': nan,
'square_root': <function square_root at 0x055246F0>
}

List of Local symbols:
{'__name__': '__main__', '__doc__': None,
'__package__': None,
'__loader__': <class '_frozen_importlib.BuiltinImporter'>,
'__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'__file__': 'C:/Python/Python361/eval_example1.py',
'acos': <built-in function acos>,
'acosh': <built-in function acosh>,
'asin': <built-in function asin>,
'asinh': <built-in function asinh>,
'atan': <built-in function atan>,
'atan2': <built-in function atan2>,
'atanh': <built-in function atanh>,
'ceil': <built-in function ceil>,
'copysign': <built-in function copysign>,
'cos': <built-in function cos>,
'cosh': <built-in function cosh>,
'degrees': <built-in function degrees>,
'erf': <built-in function erf>,
'erfc': <built-in function erfc>,
'exp': <built-in function exp>,
'expm1': <built-in function expm1>,
'fabs': <built-in function fabs>,
'factorial': <built-in function factorial>,
'floor': <built-in function floor>,
'fmod': <built-in function fmod>,
'frexp': <built-in function frexp>,
'fsum': <built-in function fsum>,
'gamma': <built-in function gamma>,
'gcd': <built-in function gcd>,
'hypot': <built-in function hypot>,
'isclose': <built-in function isclose>,
'isfinite': <built-in function isfinite>,
'isinf': <built-in function isinf>,
'isnan': <built-in function isnan>,
'ldexp': <built-in function ldexp>,
'lgamma': <built-in function lgamma>,
'log': <built-in function log>,
'log1p': <built-in function log1p>,
'log10': <built-in function log10>,
'log2': <built-in function log2>,
'modf': <built-in function modf>,
'pow': <built-in function pow>,
'radians': <built-in function radians>,
'sin': <built-in function sin>,
'sinh': <built-in function sinh>,
'sqrt': <built-in function sqrt>,
'tan': <built-in function tan>,
'tanh': <built-in function tanh>,
'trunc': <built-in function trunc>,
'pi': 3.141592653589793,
'e': 2.718281828459045,
'tau': 6.283185307179586,
'inf': inf,
'nan': nan,
'square_root': <function square_root at 0x055246F0>
}

List of names in current local scope:
['__annotations__',
'__builtins__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'acos', 'acosh',
'asin', 'asinh',
'atan', 'atan2', 'atanh',
'ceil', 'copysign', 'cos',
'cosh', 'degrees', 'e',
'erf', 'erfc', 'exp',
'expm1', 'fabs',
'factorial', 'floor',
'fmod', 'frexp', 'fsum',
'gamma', 'gcd', 'hypot',
'inf', 'isclose', 'isfinite',
'isinf', 'isnan', 'ldexp',
'lgamma', 'log', 'log10',
'log1p', 'log2', 'modf', 'nan',
'pi', 'pow', 'radians', 'sin',
'sinh', 'sqrt', 'square_root',
'tan', 'tanh', 'tau', 'trunc'
]

Below we can see, we can specify globals value as empty dictionary in eval function:

>>> print(eval('dir()', {}))
['__builtins__']

Let’s look at another example where we are allowing access to only a few of the methods from math module.

from math import *
for l in range(1, 4):
   func = input("Enter Math Function to Evaluate.\nAllowed Functions are: abs(x) and pow(x,y):\n")
   try:
      print(eval(func, {'absolute': abs, 'pow': pow}))
      except Exception as ex:
      print(ex)
      break
print('Done')

Output

Enter Math Function to Evaluate.
Allowed Functions are: abs(x) and pow(x,y):
abs(-74)
74
Enter Math Function to Evaluate.
Allowed Functions are: abs(x) and pow(x,y):
pow(2,7)
128.0
Enter Math Function to Evaluate.
Allowed Functions are: abs(x) and pow(x,y):
sqrt(47)
name 'sqrt' is not defined
Done
raja
Published on 08-Apr-2019 13:05:52
Advertisements