This eval()
function returns a result of the evaluation of a Python expression.
eval(expression[, globals[, locals]])
Here,
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.
>>> x = 1
>>> print eval('x+1')
2
>>> eval('2*2')
4
>>> eval("len('cloudyfox')")
9
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'
>>> 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'
__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