How do I import a module only when needed?

…衆ロ難τιáo~ 提交于 2021-01-27 07:10:41

问题


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

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

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.

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?


回答1:


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 takes an optional second argument specifying the package from which to import the module.

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()


来源:https://stackoverflow.com/questions/14052129/how-do-i-import-a-module-only-when-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!