Python exec() Method

The exec() method executes the Python code block passed as a string or a code object. The string is parsed as Python statements and then executed.

Syntax:

exec(object, globals, locals)

Parameters:

  1. object: (Required) Either a string, or a code object.
  2. globals: (Optional) A dictionary containing global variables.
  3. locals: (Optional) A dictionary containing local variables.

Return Value:

None.

The following example demonstrates the simple exec() method.

Example: Execute Code
exec('print("Hello World")')
Output
Hello World

In the above example, 'print("Hello World")' string is parsed as a Python statement and executed.

A string can be a multi-line code string where each line will be considered as a statement, as shown below:

Example: Execute Multi-line Code
mycode='''a=5
b=4
print('axb=', a*b)'''

exec(mycode)
Output
axb= 20

The code that is passed to the exec() method can take a user input too using the input() function.

Example: exec()
code = input("Enter Python Expression: ")
exec(code)
Output
Enter Python Expression: [print(x**2) for x in [1, 2, 3,4,5]]
1
4
9
16
25

By default, the exec() function can executes the built-in functions. For example, the following executes the abs() function.

Example: exec()
exec('print(abs(-9))')
Output
9

The below example shows all the functions that are available to exec() when no module has been imported.

Example: exec()
exec('print(dir())')
Output
['annotations', 'builtins', 'doc', 'loader', 'name', 'package', 'spec']

You can import the module and use functions of that module in the code string passed in the exec() method, as shown below.

Example:
mycode='''from math import *
a = sqrt(9)
print(a)'''

exec(mycode)
Output
3.0

If a module is imported before calling the exec() method, for instance, the math module, then all the methods of the math module will be available to use in the exec() method.

Example:
from math import *
exec('print(dir())')
Output
['annotations', 'builtins', 'doc', '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']

You can then execute the imported module's function in the exec() without having the import statement in the code string.

Example:
from math import *

mycode='''a = sqrt(9)
print(a)'''

exec(mycode)
Output
3.0

By default, all the local, built-ins, and imported module's functions can be used in the exec() method. Use globals parameter to specify global, imported module's or built-in functions that can be executed by the exec() function and use locals parameter to allow the use of local functions. For example, the following restricts the use of the sqrt() function even if we have imported it.

Example:
from math import *

mycode='''a = sqrt(9)
print(a)'''

exec(mycode, {})
Output
Traceback (most recent call last):
    exec(mycode, {})
  File "<string>", line 1, in >module>
NameError: name 'sqrt' is not defined

In the above example, we specified an empty dictionary {} as a global parameter, which indicates that no global or imported module's functions are allowed, and so calling the sqrt() function in the exec() function will throw an error. Include the sqrt() function in the global dict to allow in the exec() function, as shown below.

Example:
from math import *

mycode='''a = sqrt(9)
print(a)'''

exec(mycode, {'sqrt': sqrt})
Output
3.0

You can add built-in or custom functions to allow in the exec() function. For example, the following defines the sqroot() function that points to the sqrt() function. So, you can use the sqroot() function instead of the sqrt() function.

Example:
from math import *

mycode='''a = sqroot(9)
print(a)'''

exec(mycode, {'sqroot': sqrt})
Output
3.0

You can also restrict the use of builtins by passing the value None to the __builtins__ in the global dictionary. The following throws an error when calling built-in function print().

Example:
mycode='print("Hello World")'

exec(mycode, {'__builtins__': None})
Output
Traceback (most recent call last):
    exec(mycode, {'__builtins__': None})
  File "<string>", line 1, in >module>
TypeError: 'NoneType' object is not subscriptable

The locals parameter is used to specify local functions or variables that are allowed in the exec() method. Consider the following example.

Example:
def myfunc1():
	print('myfunc1')

def myfunc2():
	print('myfunc2')

globlsparam = {'__builtins__' : None}
localsparam = {'myfunc1': myfunc1}

exec('myfunc1', globlsparam, localsParameter) # valid
exec('myfunc2', globlsparam, localsparam) # throws error
Output
myfunc1

Traceback (most recent call last):
exec('myfunc2', globlsparam, localsparam)
    File "<string>", line 10, in >module>
NameError: name 'myfunc2' is not defined

In the above example, locals parameter contains a local function myfunc1() so the exec() function can call myfunc1() but not myfunc2() function. Thus, we can restrict the use of global and local functions using globals and locals parameters.