如何仅在需要时导入模块? [英] How do I import a module only when needed?

查看:34
本文介绍了如何仅在需要时导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing different python modules for gupshup, nexmo, redrabitt, etc. service providers.

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

所有其他模块都具有test()方法,其中的内容不同.我知道要呼叫谁的test().我想编写另一个模块 provider ,它看起来像-

All the other modules have test() method with different content in them. I know whose test() to call. I want to write another module provider, which will look like -

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

我将传递一些字符串数据作为命令行参数,该参数将具有模块的名称.

I will pass some sting data as a command line argument which will have the name of the module.

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

But I don't want to import all the modules with import providers.* and then call the method like providers.gupshup.test(). Just by knowing whose test() I am going to call at run time, how do I load only nexmo module when I want to call it's test method?

推荐答案

如果字符串中包含模块名称,则可以使用

If you have the module name in a string, you can use importlib to import the module you want as needed:

from importlib import import_module

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

import_module 带有可选的第二个参数,用于指定要从中导入模块的软件包.

import_module takes an optional second argument specifying the package from which to import the module.

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

If you additionally need to fetch a class from the module to get at the test method, you can get that from the module with 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()

这篇关于如何仅在需要时导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆