Skip to content

Instantly share code, notes, and snippets.

@cdent
Forked from FND/app.py
Last active April 16, 2018 19:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdent/ea28e1d5601639a5e8d0f9080e953e4c to your computer and use it in GitHub Desktop.
Save cdent/ea28e1d5601639a5e8d0f9080e953e4c to your computer and use it in GitHub Desktop.
custom Python module importer
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()
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')
TEST_NAME = "BAR"
print("TEST", TEST_NAME)
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