The implementation of import in Python (importlib)

PythonServer Side ProgrammingProgramming

The importlib package provides the implementation of the import statement in Python source code portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python.

This package also exposes components to implement import, making it easier for users to create their own custom objects (known as an importer) to participate in the import process.

The importlib package has an important function named as import_module()

import_module():

This function imports a module programmatically. Name of module is first parameter to the function. Optional second parameter specifies package name if any.

invalidate_caches():

This function invalidates the internal caches of finders. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module’s existence.

reload():

This function reloads a previously imported module. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

Example:

Create two Python scripts named module1.py and module2.py having same code as below:

#module1
def main():
   print ('module imported', __name__)
   return
if __name__=='__main__':
   main()

We now import these modules dynamically using importlib package.

>>> import importlib
>>> mod=importlib.import_module('module1')
>>> mod.__name__
'module1'
>>> mod=importlib.import_module('module2')
>>> mod.__name__
'module2'
>>> mod.main()
module imported module2
>>>

The importlib package contains following submodules:

importlib.abc

This module contains all of the core abstract base classes used by import. Some subclasses of the core abstract base classes are also provided to help in implementing the core ABCs

importlib.resources

This module leverages Python’s import system to provide access to resources within packages.

importlib.machinery

This module contains the various objects that help import find and load modules.

importlib.util

This module has utility code for importers. It contains the various objects that help in the construction of an importer. Following important functions are defined in it.

find_spec():

This function find the specifications for a module, relative to the specified package name. If name is for a submodule (contains a dot), the parent module is automatically imported. Name and package work the same as for import_module().

module_from_spec(spec)

Create a new module based on spec and spec.loader.create_module.

Example:

import importlib.util
def check_module(mod):
   spec = importlib.util.find_spec(mod)
   if spec is None:
      print('Module: {} not found'.format(mod))
      return None
   else:
      print('Module: {} can be imported!'.format(mod))
      return spec
   def import_module(spec):
      mod = importlib.util.module_from_spec(spec)
      spec.loader.exec_module(mod)
      return mod
if __name__ == '__main__':
   spec = check_module('notamodule')
   spec = check_module('module1')
   if spec:
      mod = import_module(spec)
      mod.main()

Output:

Module: notamodule not found
Module: module1 can be imported!
module imported module1
raja
Published on 20-Feb-2019 16:09:10
Advertisements