import 

Send to Kindle
home » snippets » python » import



Note:  The imp module bypasses all this machinery so it's better to use __import__ rather than the imp module.

Packages in Multiple Directories

Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.

While this feature is not often needed, it can be used to extend the set of modules found in a package.

My Notes: Directories you add to that list need not have an __init__.py in them. If they have an __init__.py, it isn't executed.

sys.meta_path

A list of finder objects that have their find_module() methods called to see if one of the objects can find the module to be imported. The find_module() method is called at least with the absolute name of the module being imported. If the module to be imported is contained in package then the parent package’s __path__ attribute is passed in as a second argument. The method returns None if the module cannot be found, else returns a loader

sys.meta_path is searched before any implicit default finders or sys.path.

sys.path_hooks

A list of callables that take a path argument to try to create a _finder_ for the path. If a finder can be created, it is to be returned by the callable, else raise ImportError.

Python 3.4 import machinery

Refs

Overview

sys.meta_path entries

Each object in sys.meta_path is called a "meta path finder" object

The default sys.meta_path has three meta path finders:

Importing Overview

The spec objects

Attributes

Importing Overview

Pseudocode.  Ref Loading from Finders.

module = spec.loader?.create_module?(spec) else types.ModuleType(spec.name)

# Set import-related module attributes such as __name__, __loader__, __package__, __spec__, __path__, __file__, __cached__
# Ref: https://docs.python.org/3/reference/import.html#import-related-module-attributes
module.__name__ = spec.name
module.__loader__ = spec.loader
# …

if spec.loader:
  sys.modules[spec.name] = module
  module = spec.loader.exec_module(spec.name)
else:
  assert(spec.submodule_search_locations)
  sys.modules[spec.name] = module

return sys.modules[spec.name]