How to Dynamically Load Modules or Classes in Python

27 Feb, 2020
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 methodmod.welcome("User_1") 
Output
Hi! User_1 Welcome to GfG
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 moduleclass Welcome:    def welcome(str):        print("Hi ! % s Welcome to GfG" % str)Dynamic_import.pyclass 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")OutputHi! User_1 Welcome to GfG
module.py
# class inside the moduleclass 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.pyimport impimport 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 codeif __name__ == "__main__":    mod, modCl = dynamic_imp("GFG", "addNumbers")    modCl.addNumbers(1, 2)OutputHi! User_1 Welcome to GfG
Dynamic_import.py
import impimport 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 codeif __name__ == "__main__":    mod, modCl = dynamic_imp("GFG", "addNumbers")    modCl.addNumbers(1, 2)
Output
Hi! User_1 Welcome to GfG
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python