exec () in Python

Python Methods and Functions

The exec () function is used to dynamically execute a Python program that can be either string or object code. If it is a string, the string is parsed as a set of Python statements, which are then executed, unless a syntax error occurs, and if it is object code, it is simply executed. We must be careful that return statements cannot be used outside of function definitions, even in the context of code passed to the exec () function. It does not return any value, therefore it returns None
Syntax :

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

Can take three parameters:

  • object: as mentioned, this can be a string or object code
  • globals: this can be a dictionary, and the parameter is optional
  • locals: this can be a display object and also optional

Now let`s see how this function works. In the following code, we used the object code and executed it using the exec () function. We just accepted an object parameter and omitted the other two fields. 
Example:

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

exec (prog)

Output:
Amount 5 and 10 is 15

Warning or Limitations

Before using any methods inside the exec () function, remember to that all functions support exec (). We can use the dir () function to view this. 
Example:

# The math class is used to include all
# math functions

from math import *

exec ( "print (dir ())" )

Output:

 [`__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`,` sin`, `sinh`,` sqrt`, ` tan`, `tanh`,` trunc`] 

Global and local parameters

Python allows us to restrict the use of various variables and methods using global and local parameters that may not be required. 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 that the global can be used for both fields. Let`s see how the code works by passing only a global parameter. 
Example:

# We went through an empty dictionary here

from math import *

exec ( "print (dir ())" , {})

Output:

 [`__builtins__`] 

Thus, we see that when passing an empty dictionary as a global parameter, only __builtins__ is displayed and no other math functions are displayed, as in the previous example. This means that only the __builtins__ parameter will be supported for the object parameter. This suggests that all other functions are limited at the facility. To prove this, let`s try a math function and see what happens. 
Example:

# Thrown an exception

from math import *

exec ( "print (factorial (5))" , {})

Output:

 No Output 

This example was supposed to print 120 as output, but instead it displays "No Output" and throws an exception. Although we imported the math module, the factorial () method did not work due to the constraints we set when passing in a global parameter. 
We can also allow multiple functions. Suppose we want all other math modules to be constrained except for the factorial () function. 
Example:

# 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 a user-defined name at runtime. We can change the function name from factorial () to fact () which is user-defined. 
Example:

# factorial () renamed as fact

from math import *

exec ( `print (fact (5))` , { `fact` : factorial})

Output:

 120 

Now let`s see what else we can do to pass both global and local parameters. Using local parameters, we can implement functions according to our needs. 
Example:

from math import *

exec ( "print (dir ())" , { "built" : __builtins__}, { "sum" : sum , " iter " : iter })

Output:

 [`dir`,` print`, `sum`] 

Due to this, only the sum and iter methods along with all the built-in methods. 
We can also restrict the use of __builtins__ as follows:

#__ builtins__ was restricted with None

from math import *

exec ( "print (dir ())" , { "__ builtins__" : None }, { "sum" : sum , "print" : print , "dir" : dir })

Exit:

 [`dir`,` print`, `sum`] 

Here only functions sum, print and dir will be executed inside the exec function (), not all built-in methods.

This article courtesy of Chinma Lenka . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please write in comments if you find anything wrong or if you`d like to share more information on the topic discussed above.





Get Solution for free from DataCamp guru