How to Dynamically Load Modules or Classes in Python

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 module.py and importing_mod.py in the same directory. The module.py file acts as a module to import_mod.py file.

module.py

filter_none

edit
close

play_arrow

link
brightness_4
code

# welcome method in the module 
def welcome(str):
    print("Hi ! % s Welcome to GfG" % str)

chevron_right


import_mod.py file



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing module.py file 
import module as mod
  
  
# running the welcome method
mod.welcome("User_1"

chevron_right


Output

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:

    module.py

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # class inside the module
    class Welcome:
        def welcome(str):
            print("Hi ! % s Welcome to GfG" % str)

    chevron_right

    
    

    Dynamic_import.py

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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)
            my_class.welcome('User_1')
        
    # Driver Code  
    obj = Dimport("module", "Welcome")

    chevron_right

    
    

    Output

    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.

    Dynamic_import.py

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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
        try:
            fp, path, desc = imp.find_module(name)
              
        except ImportError:
            print ("module not found: " + name)
              
        try:
        # 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:
            print(e)
              
        try:
            myclass = imp.load_module("% s.% s" % (name,
                                                   class_name), 
                                      fp, path, desc)
              
        except Exception as e:
            print(e)
              
        return example_package, myclass
          
    #  Driver code
    if __name__ == "__main__":
        mod, modCl = dynamic_imp("GFG", "addNumbers")
        modCl.addNumbers(1, 2)

    chevron_right

    
    

    Output

    Hi! User_1 Welcome to GfG



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.