What is exec() method

The exec() function is used for the dynamic execution of Python programs which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed. We must be careful that the return statements may not be used outside of function definitions not even within the context of code passed to the exec() function. It doesn’t return any value, hence returns None.

Syntax of exec() method

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

  • object: As already said this can be a string or object code
  • globals: This can be a dictionary and the parameter is optional
  • locals: This can be a mapping object and is also optional

Return:  None.

Example 1

Using the random function of the random module and calling it using exec() method. The random module generates a decimal number between 0 and 1.

Python3




if __name__ == "__main__":
  
    # Importing a module random
    import random
  
    # Using random function of random
    # module as func
    func = "random.random"
  
    # calling the function and storing
    # the value in res
    exec(f"x = {func}")
    res = x()
  
    # Printing the result
    print(res)


Output:

0.640045711797753

Example 2

Here also we are generating a decimal number between 0 and 1.

Python3




if __name__ == "__main__":
  
    # Importing a module random
    import random
  
    # Using random function of random
    # module as func
    func = "random"
  
    # calling the function and storing
    # the value in res
  
    exec(f"x = random.{func}")
    res = x()
  
    res1 = round(res, 4)
  
    # Printing the result
    print(res1)


Output:

0.6221


Call a function by a String name – Python

In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let’s say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between start(inclusive) and end(inclusive). Here, we will discuss 2 methods to solve this:

  • Python Getattr() Method
  • Python exec() Method

Similar Reads

What is Getattr() Method

Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key....

What is exec() method

...