Last active
September 21, 2022 20:59
-
-
Save pfmoore/5265772 to your computer and use it in GitHub Desktop.
A dummy finder/loader that returns *any* module name under a given prefix.
This file contains 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
"""A dummy loader implementation. | |
This is a deliberate attempt to implement an absolutely minimal finder/loader | |
combination. | |
The spec is: | |
1. If I add an entry dummy:XXX to sys.path, then that entry will be picked | |
up by my finder and used to satisfy import requests for any modules | |
starting with 'XXX'. | |
2. All modules contain "print('hello from <modulename>')" as their sole | |
content. This content is generated dynamically on demand. | |
3. All modules are also packages. So *any* import of the form | |
"import XXX.yy.xx" will be satisfied. | |
""" | |
from importlib.abc import PathEntryFinder, SourceLoader | |
def pathhook(pathentry): | |
if pathentry.startswith("dummy:"): | |
return MyFinder(pathentry[6:]) | |
raise ImportError | |
class MyFinder(PathEntryFinder): | |
def __init__(self, prefix): | |
"""Create a finder for the given prefix""" | |
self.prefix = prefix | |
def find_loader(self, fullname): | |
"""Return a loader for the module `fullname`""" | |
print("find_loader('{}')".format(fullname)) | |
if fullname.startswith(self.prefix): | |
return MyLoader(fullname), [] | |
return None, [] | |
class MyLoader(SourceLoader): | |
def __init__(self, modname): | |
self.modname = modname | |
def module_repr(self): | |
return "<Module {} (dummy)>".format(self.modname) | |
def get_data(self, path): | |
print("get_data('{}')".format(path)) | |
return b"print('hello from " + path.encode('ascii') + b"')" | |
def get_filename(self, modname): | |
# Filename is an arbitrary token. Use the module name. | |
return modname | |
def is_package(self, modname): | |
return True | |
def load_module(self, fullname): | |
mod = super().load_module(fullname) | |
mod.__path__ = ['dummy:' + fullname] | |
if __name__ == '__main__': | |
import sys | |
sys.path_hooks.append(pathhook) | |
sys.path.append('dummy:a') | |
import a | |
print(a.__path__) | |
import a.b | |
print(a.b.__path__) | |
from a.b.c import x | |
print(a.b.c.__path__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment