CosminO
CosminO

Reputation: 5226

Python get module reference from another package, knowing package and module name

How can I get the reference to a module from another package, by name?

Considering:

genericCall(packageName, moduleName, methodName):
    #Call moduleName.methodName
    #knowing that the moduleName is in packageName

Where

packageName="p1"
moduleName="m1"
methodName="f1"

Upvotes: 3

Views: 201

Answers (2)

Alexander Zhukov
Alexander Zhukov

Reputation: 4557

You'll have to import either module or package, and to do it by name, you can use __import__ or importlib.import_module.

import importlib

def genecirCall(package_name, module_name, function_name):
    # import module you need
    module = importlib.import_module('%s.%s' % (package_name, module_name))
    getattr(module, function_name)() # make a call

Note, that in this example, the module variable will be local.

Upvotes: 3

Logan Ding
Logan Ding

Reputation: 1771

__import__ provides the ability to import packages dynamically. Then after importing the package, you could use getattr to get the module object from the module name (This is called introspection in Python). Since both functions are built-in functions, you could use them without explicitly importing other packages. The doc provides more information of these built-in functions.

package = __import__(packageName)
module = getattr(package, moduleName)
method = getattr(module, methodName)
method(...)

Upvotes: 2

Related Questions