Created
March 28, 2013 15:39
-
-
Save pfmoore/5264172 to your computer and use it in GitHub Desktop.
Dummy importlib-based importer sample
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
from importlib.abc import PathEntryFinder, SourceLoader, FileLoader | |
from importlib.util import module_for_loader | |
class MyFinder(PathEntryFinder): | |
def __init__(self, pathentry): | |
"""Create a finder for the given `pathentry`""" | |
if pathentry == 'foo': | |
return | |
raise ImportError | |
def find_loader(self, fullname): | |
"""Return a loader for the module `fullname`""" | |
print("find_loader('{}')".format(fullname)) | |
return MyLoader(fullname, 'foo/__init__.py'), ['foo'] | |
class MyLoader(FileLoader, SourceLoader): | |
def module_repr(self): | |
return "!!!" | |
def get_data(self, path): | |
"""Return an open binary file object for `path`""" | |
print("get_data('{}')".format(path)) | |
return b"print('hello from foo!')" | |
if __name__ == '__main__': | |
import sys | |
sys.path_hooks.append(lambda p: MyFinder(p)) | |
sys.path.insert(0, 'foo') | |
import a | |
import a.b | |
from a.b.c import x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment