Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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"
like image 514
CosminO Avatar asked Dec 01 '25 04:12

CosminO


1 Answers

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.

like image 193
Alexander Zhukov Avatar answered Dec 03 '25 19:12

Alexander Zhukov