Open In App

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


Article Tags :