Python Module

  • What’s module
  • How to Import Module?
  • How to manipulate Module?
  • How to import module programatically?

Python inspect Module

import inspect

inspect.ismodule(module_name)

Python Import Module

python
     |--main.py
     |articles
        |--gfg.py 
# class
class GFG:
   
  # method
  def method_in():
    print("Inside Class method")
     
# explicit function   
def method_out():
  print("Inside explicit method")

Python Load Module: sys

# importing module
import sys
 
# appending a path
sys.path.append('articles')
 
# importing required module
import gfg
from gfg import GFG
 
# accessing its content
GFG.method_in()
gfg.method_out()

Python Load Module: importlib

import importlib.util
 
# specify the module that needs to be
# imported relative to the path of the
# module
spec=importlib.util.spec_from_file_location("gfg","articles/gfg.py")
 
# creates a new module based on spec
foo = importlib.util.module_from_spec(spec)
 
# executes the module in its own namespace
# when a module is imported or reloaded.
spec.loader.exec_module(foo)
 
foo.GFG.method_in()

Python Load Module: SourceFileLoader

from importlib.machinery import SourceFileLoader
 
# imports the module from the given path
foo = SourceFileLoader("gfg","articles/gfg.py").load_module()
 
foo.GFG.method_in()
foo.method_out()