-
-
Save cdent/ea28e1d5601639a5e8d0f9080e953e4c to your computer and use it in GitHub Desktop.
custom Python module importer
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
from hook import register_import_hook | |
print('calling to register') | |
register_import_hook() | |
print('registered') | |
def later(): | |
import test_foo | |
print('module', test_foo) | |
print('name', test_foo.TEST_NAME) | |
print('added thing', test_foo.added_thing) | |
if __name__ == '__main__': | |
later() |
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 sys | |
from importlib import import_module | |
class CustomImporter: | |
PATH_TRIGGER = "test_" | |
def __init__(self, path_entry): | |
print("~~ INIT", path_entry) | |
return | |
def find_module(self, fullname, path=None): | |
print("~~ FIND", type(fullname), path) | |
fh, filename, details = imp.find_module(fullname) | |
module = imp.load_module(fullname, fh, filename, details) | |
module.added_thing = custom_method | |
sys.modules[fullname] = module | |
print('inside hook') | |
module.added_thing() | |
return None | |
def register_import_hook(): | |
sys.path_hooks.append(CustomImporter) | |
sys.path.insert(0, CustomImporter.PATH_TRIGGER) | |
def custom_method(): | |
print('i am custom_method') |
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
TEST_NAME = "BAR" | |
print("TEST", TEST_NAME) |
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
TEST_NAME = "FOO" | |
print("TEST", TEST_NAME) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment