my_result = eval('2 + 4')
print(my_result) # Output is 6
Using restrictions
We can allow some functions in global scope only to evalute by using global option. Let us import our math module and find the sum of a iterable_object
This will generate error as we have used one empty dictionary ( not allowing any method ) .
import math
my_str="print(math.fsum([1,2,3,4,5]))"
eval(my_str,{})
This will work as we have allowed math.fsum to execute. Output is 15.0
import math
my_str="print(fs([1,2,3,4,5]))"
eval(my_str,{'fs':math.fsum}) 3 15.0
builtin functions
eval() has full access to all builtin functions of Python. This code will not generate any error though we have supplied an empty dictionary ({}) to globals.
While eval() is a powerful function, it poses significant security risks if used with unvalidated or untrusted input. Executing dynamically generated code can lead to vulnerabilities, such as code injection attacks. Always validate or sanitize inputs when using eval(), or avoid it in scenarios involving untrusted sources.