Skip to content Skip to sidebar Skip to footer

How Do I Import A Module Only When Needed?

I am writing different python modules for gupshup, nexmo, redrabitt, etc. service providers. #gupshup.py class Gupshup(): def test(): print 'gupshup test' All the othe

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

Post a Comment for "How Do I Import A Module Only When Needed?"