Menu Close

Python exec() Function

Python exec function

Here, we will learn about the Python exec function to execute specified python code. In Python, the exec() function provides a facility to execute a dynamically created program or a code object.

In the previous tutorial, we have seen the Python eval function to evaluate valid python code. In this guide, we will understand Python exec built-in function along with various examples, so that you can understand the python exec function very easily.

Python exec() function

Python exec function is a built-in python function that is used to execute specified python code. The main difference between the Python exec() function and the Python eval() function is, the exec function accepts large code but the eval function accepts only a single expression.

Syntax

The syntax of the Python exec method is:-

exec(objects, globals, locals)

Parameters

The exec() function accepts three parameters.

  • object:- A string or code object.
  • globals:- Optional. A Dictionary containing global parameters.
  • locals:- Optional. A Dictionary containing local parameters.

Return Value

exec() function in Python does not return any value. It returns None.

Python exec example

Here we will go through the python exec method along with various examples with easy explanations.

Example: Using Python exec() function with single param

Use the exec function with a single parameter. You have to remember one thing always, the first parameter of the exec() function always represents the string or code object.


string = 'x = 10\ny = 15\nprint("X is:- ",x)\nprint("Y is:- ",y)\nprint("Sum of {} and {} is:- {}".format(x,y,x+y))'
exec(string)

Output

X is:-  10
Y is:-  15
Sum of 10 and 15 is:- 25

Global and Local Variables

Python allows us to restrict the use of python built-in functions or methods and attributes by using the global and local parameters. The global parameter overtakes if the local is missing, which means you can say that global is the work of both of the fields.

Let’s see an example to understand global and local parameters.

Example:


from math import *
exec('print(factorial(5))', {})

Output

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

The above example should have printed 120 instead of error but it does not display any output, raise an exception, we have imported all the functions of the math module. We will get an exception because we passed the global parameters.

To solve the above problem, we have to pass the math factorial method as a global parameter.

Suppose we want to restrict all the math functions except the factorial method.

Example:

from math import *
exec("print(factorial(5))", {'factorial': factorial})

The output will be:- 120

Even you can change the name of the key in the dictionary.

Example:

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

The output will be:- 120

Let’s what happens, If we pass both global and local parameters in the python exec method.

Example:

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

The output will be:- [‘cos’, ‘sum’]

In the above example, all the built-in functions, as well as sum and cos functions have been executed.

Conclusion

In this tutorial, you have learned the python exec function to execute dynamically created python code or code objects. This is the best python built-in function to execute a large amount of code. You always remember that the exec function in Python is completely different from the eval function in Python.

If this article helped you, please keep visiting for further python built-in functions tutorials.

Other Python built-in functions


For more information:- Click Here

Python frozenset Function
Python float() Function

Related Posts