We can allow some functions in global scope only to execute 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
str="print(math.fsum([1,2,3,4,5]))"
exec(str,{})
This will work as we have allowed math.fsum to execute. Output is 15.0
import math
str="print(fs([1,2,3,4,5]))"
exec(str,{"fs":math.fsum}) # 15.0
builtin functions
exec() 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. Output is 15
str="print(sum([1,2,3,4,5]))"
exec(str,{}) # 15
Difference Between eval() and exec() in Python
eval() is used to evaluate a single Python expression and return the result. It's suitable for simple evaluations of Python expressions that have a return value.
exec() is used for executing dynamically generated Python code which can be more complex than a single expression. It can execute multiple statements and even complex code structures, such as loops or function definitions, but it doesn't return the result.
Take precaution by not allowing un-cleaned code to get executed through exec(). There is a potential danger in allowing codes to get executed without proper check.
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery,
and web development at plus2net. The tutorials focus on clear explanations, working
examples, and code that readers can test and adapt while learning.