Monday, November 18, 2024
Google search engine
HomeLanguagesHow to Dynamically Load Modules or Classes in Python

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




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


import_mod.py file




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


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




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

    
    

    Dynamic_import.py




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

    
    

    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




    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)

    
    

    Output

    Hi! User_1 Welcome to GfG
RELATED ARTICLES

Most Popular

Recent Comments