Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference to module by string name and call its method by string name?

Tags:

python

The modules are already imported in the current module ( no need of dynamic import ), and have an ALIAS name. The requirement is to get reference to the module by its alias name, and call its function

current module :

import libraries.mymaths.products as myproductlib

def call_func(module_name,method_name):
    # module_name = 'myproductlib' , method_name='mult'
    # how to call myproductlib.mult here ?

getattr(MODULE_REF, method_name) would help me to get reference to method, but how to get reference to module by its alias name ?

like image 965
DhruvPathak Avatar asked Jun 17 '13 07:06

DhruvPathak


People also ask

How do you call a function by its string name in Python?

Use eval() to call a function by its name as a string Call eval(string) with string as the function name and "()" .

How do you find the methods of a module?

You can use dir(module) to see all available methods/attributes.

Which function is used to find out which names a module defines?

The dir() function is used to find out all the names defined in a module. It returns a sorted list of strings containing the names defined in a module.


1 Answers

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.

like image 78
BrenBarn Avatar answered Sep 28 '22 20:09

BrenBarn