Open In App
Related Articles

How to Dynamically Load Modules or Classes in Python

Like Article
Save Article
Report issue
Python provides a feature to create and store classes and methods and store them for further use. The file containing these sets of methods and classes is called a module. A module can have other modules inside it. Note: For more information, refer to Python Modules Example: A simple example of importing a module is shown below in which, there are 2 files that are and in the same directory. The file acts as a module to file.
# welcome method in the module 
def welcome(str):
    print("Hi ! % s Welcome to GfG" % str)

# importing file 
import module as mod
# running the welcome method

Hi! User_1 Welcome to GfG

Dynamically Loading Modules or Classes

The modules added in the above code are importing modules statically i.e in compile time. In Python we can import modules dynamically by two ways

  • By using __import__() method: __import__() is a dunder method (methods of class starting and ending with double underscore also called magic method) and all classes own it. It is used to import a module or a class within the instance of a class. There is an example on this method given as follows, in which we will be importing a module dynamically. The module file is now modified as:
    # class inside the module
    class Welcome:
        def welcome(str):
            print("Hi ! % s Welcome to GfG" % str)
    class Dimport:
        def __init__(self, module_name, class_name):
            #__import__ method used
            # to fetch module
            module = __import__(module_name)
            # getting attribute by
            # getattr() method
            my_class = getattr(module, class_name)
    # Driver Code  
    obj = Dimport("module", "Welcome")
    Hi! User_1 Welcome to GfG
  • Using the imp module: Modules can be imported dynamically by the imp module in python. The example below is a demonstration on the using the imp module. It provides the find_module() method to find the module and the import_module() method to import it.
    import imp
    import sys
    # dynamic import 
    def dynamic_imp(name, class_name):
        # find_module() method is used
        # to find the module and return
        # its description and path
            fp, path, desc = imp.find_module(name)
        except ImportError:
            print ("module not found: " + name)
        # load_modules loads the module 
        # dynamically ans takes the filepath
        # module and description as parameter
            example_package = imp.load_module(name, fp,
                                              path, desc)
        except Exception as e:
            myclass = imp.load_module("% s.% s" % (name,
                                      fp, path, desc)
        except Exception as e:
        return example_package, myclass
    #  Driver code
    if __name__ == "__main__":
        mod, modCl = dynamic_imp("GFG", "addNumbers")
        modCl.addNumbers(1, 2)
    Hi! User_1 Welcome to GfG

Last Updated : 27 Feb, 2020
Like Article
Save Article
Share your thoughts in the comments
Similar Reads