How to Call a Function by Its Name Using a String in Python
In Python programming, there are times when you need to call a function by its name which is stored in a string variable. This can be particularly useful in cases where you have a set of functions, and you want to invoke them dynamically based on user input or other conditions.
In this blog post, we will explore how to call a function using a string with the function’s name, providing you with a clear and organized method to achieve this.
The Problem: Calling Functions Dynamically
Imagine you have a module named foo
which includes a function called bar
. You want to invoke this function, but instead of calling it directly, you have only the name of the function as a string:
import foo
func_name = "bar"
call(foo, func_name) # How do we make this work?
You might be wondering how to convert this string into a functional call. The solution lies in Python’s built-in function getattr
.
The Solution: Using getattr
What is getattr
?
getattr
is a built-in function in Python that allows you to retrieve an attribute (in this case, a function) from an object (a module, class, or instance) dynamically. This means you can specify the name of the attribute as a string and get back the actual object associated with that name.
How to Use getattr
to Call Functions
Here’s how you can use getattr
to call the function stored in the string:
-
Import the Module: First, make sure to import the module that contains the function you want to call.
import foo
-
Retrieve the Function: Use
getattr
to get the function from the module using its name as a string.bar = getattr(foo, 'bar')
-
Call the Function: Now that you have the function referenced, you can call it just like any regular function.
result = bar() # This invokes foo.bar()
Example Code
Here is the complete working code:
import foo
# The name of the function as a string
func_name = "bar"
# Retrieve the function using getattr
bar = getattr(foo, func_name)
# Call the function
result = bar() # This will call foo.bar()
Key Points to Remember
-
getattr
can be used not only for module-level functions but also for class instance methods and more. -
If the attribute (function) does not exist,
getattr
will raise anAttributeError
. You can provide a default value to avoid this using a second argument ingetattr
.bar = getattr(foo, 'bar', None) # This will return None if 'bar' does not exist.
Additional Resources
For more details on getattr
, you can check the official Python documentation here.
Conclusion
Dynamic function calling using a string representation of function names can significantly enhance the flexibility of your code. With the help of getattr
, you can easily manage and invoke functions based on variable names, making your programs more adaptable and user-friendly.
Feel free to try this method with your own functions and modules, and take advantage of this powerful capability in Python!