Search code examples
pythonpython-importpython-module

What is the difference between `sys.meta_path` and `sys.path_hooks` importer objects?


Using importlib, what is the difference between "Meta Path Finder" (found by traversing over sys.meta_path) and Path Entry Finder" (found by traversing over sys.path_hooks)?

The first type is called upon begin of an import, but when is the second type used? Do both return a spec object?

I want to implement a customized import, where a module can be imported from sources other than *.py or *.pyc, e.g. from a stream. How can this be done?


Solution

  • sys.path_hooks returns a finder factory.

    Path hooks are called as part of sys.path (or package.__path__ ) processing

    as we read in PEP 302 relevant part which you should read to do what you want.

    Coming to speak of, we use a custom hook in my code but I would not recommend you to copy it verbatim (I am really not sure about the hocus pocus we do with init files)

    However the process is a bit like in there - the find_module method returns self or None depending on what you want to accept as a module and the load_module method proceeds to load that by compiling the code and assigning it an entry into sys.modules. By replacing those parts you can pretty much load whatever you want.

    Related: