An importlib reimplementation of imp.find_module (for our purposes).
(name, path=None)
| 43 | |
| 44 | |
| 45 | def _find_module(name, path=None): |
| 46 | """An importlib reimplementation of imp.find_module (for our purposes).""" |
| 47 | |
| 48 | # It's necessary to clear the caches for our Finder first, in case any |
| 49 | # modules are being added/deleted/modified at runtime. In particular, |
| 50 | # test_modulefinder.py changes file tree contents in a cache-breaking way: |
| 51 | |
| 52 | importlib.machinery.PathFinder.invalidate_caches() |
| 53 | |
| 54 | spec = importlib.machinery.PathFinder.find_spec(name, path) |
| 55 | |
| 56 | if spec is None: |
| 57 | raise ImportError("No module named {name!r}".format(name=name), name=name) |
| 58 | |
| 59 | # Some special cases: |
| 60 | |
| 61 | if spec.loader is importlib.machinery.BuiltinImporter: |
| 62 | return None, None, ("", "", _C_BUILTIN) |
| 63 | |
| 64 | if spec.loader is importlib.machinery.FrozenImporter: |
| 65 | return None, None, ("", "", _PY_FROZEN) |
| 66 | |
| 67 | file_path = spec.origin |
| 68 | |
| 69 | # On namespace packages, spec.loader might be None, but |
| 70 | # spec.submodule_search_locations should always be set — check it instead. |
| 71 | if isinstance(spec.submodule_search_locations, importlib.machinery.NamespacePath): |
| 72 | return None, spec.submodule_search_locations, ("", "", _PKG_DIRECTORY) |
| 73 | |
| 74 | if spec.loader.is_package(name): # non-namespace package |
| 75 | return None, os.path.dirname(file_path), ("", "", _PKG_DIRECTORY) |
| 76 | |
| 77 | if isinstance(spec.loader, importlib.machinery.SourceFileLoader): |
| 78 | kind = _PY_SOURCE |
| 79 | |
| 80 | elif isinstance( |
| 81 | spec.loader, ( |
| 82 | importlib.machinery.ExtensionFileLoader, |
| 83 | importlib.machinery.AppleFrameworkLoader, |
| 84 | ) |
| 85 | ): |
| 86 | kind = _C_EXTENSION |
| 87 | |
| 88 | elif isinstance(spec.loader, importlib.machinery.SourcelessFileLoader): |
| 89 | kind = _PY_COMPILED |
| 90 | |
| 91 | else: # Should never happen. |
| 92 | return None, None, ("", "", _SEARCH_ERROR) |
| 93 | |
| 94 | file = io.open_code(file_path) |
| 95 | suffix = os.path.splitext(file_path)[-1] |
| 96 | |
| 97 | return file, file_path, (suffix, "rb", kind) |
| 98 | |
| 99 | |
| 100 | class Module: |
no test coverage detected
searching dependent graphs…