16

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 ?

2 Answers 2

24

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.

Sign up to request clarification or add additional context in comments.

Comments

12

BrenBarn's globals() solution works with the module name, ALIASESED or not, only if the import is located in this module (the one currently running).

If you still want to get hold of the module by its unaliased name (e.g. it was imported earlier, from some other module), get it from sys.modules with a FQN module name like "apackage.somemodule":

>>> import sys
>>> import libraries.mymaths.products as myproductlib

>>> globals()["myproductlib"] == sys.modules["libraries.mymaths.products"]
True

1 Comment

While both answers work, I prefer this one because it does not require an import of the module (which would appear unused if not used anywhere else).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.