如何仅在需要时导入模块?

时间:2012-12-27 09:12:11

标签: import python-2.7

我正在为gupshup,nexmo,redrabitt等服务提供商编写不同的python模块。

#gupshup.py
class Gupshup():
    def test():
        print 'gupshup test'

所有其他模块都有test()方法,其中包含不同的内容。我知道哪个测试()要打电话。我想写另一个模块 provider ,它看起来像 -

#provider.py
def test():
    #call test() from any of the providers

我会将一些sting数据作为命令行参数传递,该参数将具有模块的名称。

但我不想使用import providers.*导入所有模块,然后调用类似providers.gupshup.test()的方法。只要知道我将在运行时调用哪个test(),当我想调用它的测试方法时,如何只加载nexmo模块?

1 个答案:

答案 0 :(得分:2)

如果您在字符串中有模块名称,则可以使用importlib根据需要导入所需的模块:

from importlib import import_module

# e.g., test("gupshup")
def test(modulename):
    module = import_module(module_name)
    module.test()

import_module接受一个可选的第二个参数,指定从中导入模块的包。

如果您还需要从模块中获取类以获取测试方法,则可以使用getattr从模块中获取该类:

# e.g., test("gupshup", "Gupshup")
def test(modulename, classname):
    module = import_module(module_name)
    cls = getattr(module, classname)
    instance = cls()  # maybe pass arguments to the constructor
    instance.test()
相关问题