How to call a function of a module by using its name (a string) in Python

In this tutorial, you will learn methods to call a module’s function by using its name in Python. Generally, we cannot write a mathematical expression in the form of a string to do calculations, we can only use the int or float datatypes for doing mathematical calculations. So, in this tutorial, we will learn the methods of converting a string to a function in Python programming. Read the following text very carefully to learn and explore new ways of coding.

Convert string to function using eval() function:

Example 1:

In example 1, we will see how can we convert a mathematical expression written as a string in Python to a function with the help of the eval() function. Here eval is the short form of evaluate.

# define variables
a=12
b=5
# make a string using the variables
c="(a-b)*b+1"
# convert the string to an executable function using the eval() function
output=eval(c)
print("The output of the expression is:",output)
Output:
The output of the expression is: 36

Example 2:

In example 2, we will convert a function containing a for loop, to a string, then with the help of the eval() function we will convert this string to an executable function in Python. We will write the string inside the eval() function and add the “()” parenthesis using the + operand, i.e…… eval(string + "()").

# create a function using a for loop
def square():
    for i in range(6):
        print(i*i)
# convert the function to string
# square of first five numbers
a="square"
# convert the string to function using the eval() function
eval(a+"()")
Output:
0
1
4
9
16
25

Here, the eval() function converted the (a+"()") to a then, it printed the value of the function to print the square of the first 5 numbers. This is how we converted a string to an executable function.

Convert string to function using getattr() function:

Example:

In this example, we will use the getattr() function to call a function of a module by using its name in Python. Here, we will convert the sqrt module of python into a string and pass it as an argument in the getattr() function to calculate the square root of a number. In this example, we have taken 4 as the number.

# import the math library
import math
# convert the square-root function to string
module = "sqrt"
# using getattr() function to covert the string to function
string_to_function= getattr(math, module)
# command to print square-root of 4
squareroot = string_to_function(4)
# print output
print(squareroot)
Output:
2.0

So, this is how you can convert a string to an executable function using eval() and getattr() functions in Python.

Leave a Reply

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