python - Calling a function of a module by using its name (a string)

ID : 409

viewed : 117

Tags : pythonobjectpython





Top 5 Answer for python - Calling a function of a module by using its name (a string)

vote vote

98

Assuming module foo with method bar:

import foo method_to_call = getattr(foo, 'bar') result = method_to_call() 

You could shorten lines 2 and 3 to:

result = getattr(foo, 'bar')() 

if that makes more sense for your use case.

You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.

vote vote

85

locals()["myfunction"]() 

or

globals()["myfunction"]() 

locals returns a dictionary with a current local symbol table. globals returns a dictionary with global symbol table.

vote vote

76

Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like:

module = __import__('foo') func = getattr(module, 'bar') func() 
vote vote

66

Just a simple contribution. If the class that we need to instance is in the same file, we can use something like this:

# Get class from globals and create an instance m = globals()['our_class']()  # Get the function (from the instance) that we need to call func = getattr(m, 'function_name')  # Call it func() 

For example:

class A:     def __init__(self):         pass      def sampleFunc(self, arg):         print('you called sampleFunc({})'.format(arg))  m = globals()['A']() func = getattr(m, 'sampleFunc') func('sample arg')  # Sample, all on one line getattr(globals()['A'](), 'sampleFunc')('sample arg') 

And, if not a class:

def sampleFunc(arg):     print('you called sampleFunc({})'.format(arg))  globals()['sampleFunc']('sample arg') 
vote vote

57

Given a string, with a complete python path to a function, this is how I went about getting the result of said function:

import importlib function_string = 'mypackage.mymodule.myfunc' mod_name, func_name = function_string.rsplit('.',1) mod = importlib.import_module(mod_name) func = getattr(mod, func_name) result = func() 

Top 3 video Explaining python - Calling a function of a module by using its name (a string)







Related QUESTION?