Last active
December 22, 2021 23:45
-
-
Save Xion/5358603 to your computer and use it in GitHub Desktop.
"No-op" import hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import imp | |
import inspect | |
import sys | |
__all__ = [] | |
class PassthroughImporter(object): | |
"""Import hook that simulates the standard import flow | |
that happens when we don't use import hooks at all. | |
While not very useful on its own, the hook can serve as | |
a template for injecting custom logic into the import process. | |
""" | |
def find_module(self, fullname, path=None): | |
if '.' in fullname: | |
parent, name = fullname.rsplit('.', 1) | |
find_path = self._import(parent).__path__ | |
else: | |
name = fullname | |
find_path = path | |
try: | |
imp.find_module(name, find_path) | |
except ImportError: | |
return None # couldn't find module, let Python try next importer | |
self.path = path | |
return self | |
def load_module(self, fullname): | |
imp.acquire_lock() | |
try: | |
return self._import(fullname) | |
finally: | |
imp.release_lock() | |
def _import(self, fullname): | |
try: | |
return sys.modules[fullname] | |
except KeyError: | |
pass | |
# for dotted names, apply importing procedure recursively | |
if '.' in fullname: | |
package, module = fullname.rsplit('.', 1) | |
pkg_obj = self._import(package) | |
path = pkg_obj.__path__ | |
else: | |
module = fullname | |
path = self._path | |
file_obj, pathname, desc = imp.find_module(module, path) | |
try: | |
mod_obj = imp.load_module(fullname, file_obj, pathname, desc) | |
sys.modules[fullname] = mod_obj | |
return mod_obj | |
finally: | |
if file_obj: | |
file_obj.close() | |
# Optional PEP302 methods | |
def is_package(self, fullname): | |
return hasattr(self._import(fullname), '__path__') | |
def get_code(self, fullname): | |
return compile(self.get_source(fullname)) | |
def get_source(self, fullname): | |
return inspect.getsource(self._import(fullname)) | |
sys.meta_path.append(PassthroughImporter()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment