Search code examples
python-importlib

How to force importlib find_loader to use exclusively a specific path?


I'm trying to re-implement some code based on the imp module to to use importlib instead. There is a subtle difference between the functions imp.find_module and importlib.find_loader:

# Using imp find_module
>>> import imp
>>> imp.find_module("abc", ["some/path/module.py"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python3.3/imp.py", line 220, in find_module
    raise ImportError(_bootstrap._ERR_MSG.format(name), name=name)
ImportError: No module named 'abc'

# Using import find_loader
>>> import importlib
>>> loader = importlib.find_loader("abc", ["some/path/module.py"])
>>> loader.path
'/usr/lib64/python3.3/abc.py'

It looks like importlib is falling back to system libraries, whilst imp.find_module is using the path parameter in an exclusive way, which ends up raising an exception.

How to force importlib.find_loader to use exclusively a specific path?


Solution

  • I found that the answer is not to use find_loader but to use instead the importlib.machinery.PathFinder class to lookup for modules in specific paths.