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 | if spec.loader.is_package(name): |
| 70 | return None, os.path.dirname(file_path), ("", "", _PKG_DIRECTORY) |
| 71 | |
| 72 | if isinstance(spec.loader, importlib.machinery.SourceFileLoader): |
| 73 | kind = _PY_SOURCE |
| 74 | |
| 75 | elif isinstance( |
| 76 | spec.loader, ( |
| 77 | importlib.machinery.ExtensionFileLoader, |
| 78 | importlib.machinery.AppleFrameworkLoader, |
| 79 | ) |
| 80 | ): |
| 81 | kind = _C_EXTENSION |
| 82 | |
| 83 | elif isinstance(spec.loader, importlib.machinery.SourcelessFileLoader): |
| 84 | kind = _PY_COMPILED |
| 85 | |
| 86 | else: # Should never happen. |
| 87 | return None, None, ("", "", _SEARCH_ERROR) |
| 88 | |
| 89 | file = io.open_code(file_path) |
| 90 | suffix = os.path.splitext(file_path)[-1] |
| 91 | |
| 92 | return file, file_path, (suffix, "rb", kind) |
| 93 | |
| 94 | |
| 95 | class Module: |
no test coverage detected