Open In App
Related Articles

exec() in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

exec() function is used for the dynamic execution of Python programs which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed. We must be careful that the return statements may not be used outside of function definitions not even within the context of code passed to the exec() function. It doesn’t return any value, hence returns None

Python exec() Syntax

exec(object[, globals[, locals]])

Parameters:

  • object: As already said this can be a string or object code
  • globals: This can be a dictionary and the parameter is optional
  • locals: This can be a mapping object and is also optional

How exec() works in Python?

In this example, we can see dynamic execution in Python using the exec() function. It demonstrates the ability to execute code contained in an object dynamically, showcasing the concept of dynamic execution in Python.

Python3

prog = 'print("The sum of 5 and 10 is", (5+10))'
exec(prog)

                    

Output
The sum of 5 and 10 is 15

Warning or Limitations

Before using any methods inside the exec() function one must keep in mind about what all functions do exec() support. To view this we may use dir() function. 

In this example, we can see dynamic execution in Python as the dir() function is executed within the exec() function, illustrating the concept of dynamic execution in Python.

Python3

# The math class is used to include all the
# math functions
from math import *
exec("print(dir())")

                    

Output
['__annotations__', '__builtins__', '__cached__', '__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', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

Global and Local Parameters

Python allows us to restrict the use of various variables and methods by the use of global and local parameters, which might not be needed. These local and global parameters are used for local or global variables mainly dictionaries. The global parameter overtakes if the local is missing which means global can be used for both fields. Let’s see how the code works on passing only the global parameter. 

Python3

# Here we have passed an empty dictionary
from math import *
exec("print(dir())", {})

                    

Output
['__builtins__']

So we see that on passing an empty dictionary as a global parameter, only the __builtins__ is displayed and no other math functions are displayed as in the previous example. This means that only the __builtins__ will be supported for the object parameter. This suggests that all other functions are restricted on the object. To prove it let’s try to work with a math function and see what happens. 

Python3

# An exception will be raised
from math import *
exec("print(factorial(5))", {})

                    

This example should have printed 120 as output but instead, it displays No Output and raises an exception. Although, we have imported the math module the factorial() method failed to work because of restrictions we have set by passing the global parameter. 
We can also allow a few of the many functions to execute. Suppose we want all other math modules to be restricted except the factorial() function. 

Python3

# factorial() will be executed
from math import *
exec("print(factorial(5))", {"factorial":factorial})

                    

Output
120

We can also change the name of these predefined methods and give them user-defined name during execution. We can change the name of the function from factorial() to fact(), which is user-defined. 

Python3

# factorial() renamed as fact
from math import *
exec('print(fact(5))', {'fact': factorial})

                    

Output
120

In this scenario, by passing both global and local parameters, we can tailor the behavior of executed code to our specific requirements, showcasing the versatility of dynamic execution in Python.

Python3

from math import *
exec("print(dir())", {"built" : __builtins__}, {"sum": sum, "iter": iter})

                    

Output
['iter', 'sum']

Dynamic execution in Python allows the execution of specific methods such as sum() and iter() along with built-in methods inside the exec() function, demonstrating the flexibility of dynamic execution in Python. Through this, only the sum, and iter methods along with all the built-in methods can be executed inside exec() function. We can also restrict the use of __builtins__ like this:

Python3

#__builtins__ has been restricted using None
from math import *
exec("print(dir())", {"__builtins__" : None}, {"sum": sum, "print": print, "dir": dir})

                    

Output
['dir', 'print', 'sum']



Last Updated : 29 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads