import math # Suppose we have a module called "math" with a function called "sqrt" # We don't know the name of the function in advance, so we use a variable to store it func_name = "sqrt" # Use getattr to retrieve the function from the module func = getattr(math, func_name) # Call the function result = func(4) print(result) # Output: 2.0
To call a function of a module by using its name in Python, you can use the getattr function.
Alternatively, you can also use the globals() function to retrieve the function from the global namespace. Here is an example of how to do this:
import math # Suppose we have a module called "math" with a function called "sqrt" # We don't know the name of the function in advance, so we use a variable to store it func_name = "sqrt" # Use globals() to retrieve the function from the global namespace func = globals()[func_name] # Call the function result = func(4) print(result) # Output: 2.0*Note that in both cases, you will need to import the module that contains the function you want to call.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.