Import system of Python

The import keyword in Python invokes the Python import system which first looks up the sys.modules using the module name as the key. If the lookup fails it uses a set of finders and loaders to find, load and execute the module.

Physical Design Updated 19 Sep 2019 1 min read

Overview

  • The import keyword in Python loads a Python package, a Python sub-package or a Python module and introduces their namespace into the current scope.
  • A module can be imported using the Python package importlib as well through its method import_module().
  • When import is used against a module name, the module is searched, found and loaded by a set of finders and loaders.

The import system of Python

Searching a Python module

  • The module name encountered in the Python import statement is first made a lookup in the dictionary sys.modules.
  • sys.modules acts a cache for the modules.
  • If the lookup is successful the module object is loaded from the dictionary. If the lookup on sys.modules fails, the module is searched further.
  • When the Python's import system gets a None value while doing a look up for a module name, it raises a ModuleNotFoundError.

Finding a Python Module

  • A finder uses a strategy and finds the given module in the system where Python is installed.
  • Upon successfully resolved a given module to a path - a finder returns a module specification, which contains the information about the module to be loaded.

Loading a Python Module

  • Using the module specification a loader loads the python module and executes the module. Remember, a Python module contains both executable statements and definitions like function definitions.
  • A class can combine the responsibilities of a finder and a loader, which is called an importer.