Python - how to pass a method as an argument to call a method from another library

I want to pass a method as an argument that will call such a method from another python file as follows:

file2.py

def abc():
    return 'success.'

main.py

import file2
def call_method(method_name):
    #Here the method_name passed will be a method to be called from file2.py
    return file2.method_name()

print(call_method(abc))

I expect to return success.

If you call the method in the same file (main.py), I notice that it is working. However, for a case like the one above, where it involves passing an argument called from another file, how can I do this?

+4
source share
1 answer

You can use getattrto get a function from a module using the following line:

import file2
def call_method(method_name):
    return getattr(file2, method_name)()

print(call_method('abc'))
+7
source

Source: https://habr.com/ru/post/1694416/


All Articles