ScanSkill

eval

This eval() function returns a result of the evaluation of a Python expression.

Syntax

eval(expression[, globals[, locals]])

Here,

  • expression: Required. The arguments are Unicode or Latin-1 encoded strings.
  • globals: Optional. A dictionary that defines the namespace in which the expression is evaluated.
  • locals: Optional. A dictionary of the local namespace.

Note: The expression argument is parsed and evaluated as a Python expression (technically a condition list) using the globals and locals dictionaries as global and local namespace.

Examples

  • General use case
>>> x = 1
>>> print eval('x+1')
2
>>> eval('2*2')
4
>>> eval("len('cloudyfox')")
9
  • Accessing the global namespace with eval()

You can access the global namespace using eval(). This is a potential hazard of eval() function.

>>> import os
>>> eval("os.getcwd()")
'/home/sagar/Downloads'
  • Preventing and bypassing global dictionary access using the argument
>>> import os
>>> eval("os.getcwd()", {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'os' is not defined

>>> # bypassing using __import__ function
>>> eval("__import__('os').getcwd()", {})
'/home/sagar/Downloads'
  • Preventing eval from importing modules (or __builtins__)
>>> # this example shows how to prevent eval from importing any modules
>>> eval('__import__("os").getcwd()', {'__builtins__': {}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name '__import__' is not defined

>>> from math import *
>>> eval('sqrt(49)', {})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'sqrt' is not defined

Here, {} expression as globals prevents using math module, even we import math module in the program.

To make certain methods available do as followings:

>>> from math import *
>>> eval('square(49)', {'square': sqrt, 'power': pow})
7.0