Actual purpose of exec() in Python

In this tutorial, we will discuss exec() in Python, which is responsible for the dynamic execution of a string or an object.

Syntax for exec()

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

object- It can be an object or a string

globals- It is optional and is a dictionary

locals- It is also optional  and is a mapping object

Program to implement

Let’s work on a simple program to implement exec() function. We have created a string named as str and then executed it-

str='print("Hello World")'
exec(str)
Hello World

So we can observe that there is a string named as str which functions to print a string that is Hello World.

Functions in exec()

Sometimes, we come across some errors while using exec() function, we need to check the function and its syntax. We can do this using this snippet-

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

So we can use these functions and let’s try to implement the remainder function.

An example of exec()

So we will try to implement exec() function using remainder to find the remainder when 70 is divided with 2.

from math import *
exec("print(rem(70,2))", {"rem":remainder})
0.0

We have passed remainder as a parameter that restricts all other math functions except for remainder.

This is how we can use exec() function in Python to find the remainder and also implement other functions of other modules.

I hope this tutorial was helpful to understand the purpose of exec() function in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *