BlogsDope image BlogsDope

Python exec() function

Feb. 28, 2021 PYTHON FUNCTION 3285

If you want to perform dynamic execution of your Python code, then the Python exec() function is the best option for you. This built-in function executes the dynamically created program which can either be a string or a code object.

Python exec() Syntax

The following is the syntax of the exec() method: 

 exec(object, globals, locals)

Python exec() Parameters

The exec() function takes the following three parameters:
  1. object: This is the code to be evaluated. It can be a string or a code object. 
  2. globals (optional): A dictionary containing global parameters.
  3. locals (optional): A mapping object containing local parameters. Dictionary is the standard and commonly used mapping type in Python.

Return value of exec()

The exec() method does not return any value, hence its return value is None. It simply executes the code that is passed as a paramter dynamically within the program.

Python exec() Examples

exec() with Strings

a = 5
st = "print(a*2)"
exec(st)

Output:

10

exec() without global or local parameters

When we do not pass any global and local parameters, the exec() method gives the default available functions as per the package imported into the program. 
from math import *
st = "print(dir())"
exec(st)

Output:

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'st', 'tan', 'tanh', 'tau', 'trunc'] 

exec() with global parameters

All the variables that are passed as globals in a dictionary will be available to exex() function at execution time and any globals defined outside the dictionary won't be available to the function. 

a = 5
b = 10
exec("print(a+b)", {'a':a})

Output:

​Traceback (most recent call last):
 File "<string>", line 3, in <module>
File "<string>", line 1, in <module>
NameError: name 'b' is not defined

If we declare the global variable 'b' inside the globals dictionary, the exec() method can access it.

a = 5
b = 10
exec("print(a+b)", {'a':a, 'b':b})

Output:

​15

exec() with local parameters

The variables passed in the third dictionary are treated as local parameters.

exec("print(a+b)", {}, {'a':5, 'b':10})

Output:

15

We can also restrict the usage of various functions form the imported module by using the local parameter and implementing only those functions that we need.

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

Output:

​['iter', 'sum']

In this way we have seen the functionalities of the Python exec() method and how it can be used to execute expressions dynamically in Python.


Liked the post?
Zealous Learner.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).