How to get reference to module by string name and call its method by string name?
To get the module, you can use globals
. To get the function, use getattr
:
getattr(globals()[module_name], function_name)
Importing a module just binds the module object to a name in whatever namespace you import it in. In the usual case where you import at the top level of the module, this means it creates a global variable.
Get it from sys.modules
with a FQN module name like "apackage.somemodule"
:
import sys
getattr(sys.modules[module_name], function_name)
Use this if the module name and/or function may not exist:
mod = sys.modules.get(module_name)
fn = mod and getattr(mod, function_name, None)