How do I call a function, using a string with the function's name? For example: import foo func_name = "bar" call(foo, func_name) # calls foo.bar()

In Python, you can achieve this using the built-in getattr() function. This function allows you to retrieve an attribute or method of an object by its name as a string. Here's how you can call a function using a string with the function's name:

python

def bar():
    print("Inside bar()")

def call(obj, func_name):
    func = getattr(obj, func_name)
    func()

class Foo:
    def bar(self):
        print("Inside Foo.bar()")

# Using the call function to call a method
func_name = "bar"
call(Foo(), func_name)  # Calls Foo.bar()

# Using the call function to call a regular function
func_name = "bar"
call(globals(), func_name)  # Calls the global bar()

In this example:

    The bar() function is a regular function.
    The Foo class has a bar() method.
    The call() function takes an object and a function name, retrieves the function using getattr(), and then calls it.

When you call call(Foo(), func_name), it calls the bar() method of the Foo class. When you call call(globals(), func_name), it calls the global bar() function.

Keep in mind that using strings to dynamically call functions can make your code less readable and harder to debug. It's recommended to use this approach sparingly and only when you have a specific need for dynamic function calls.

Comments