问题
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