Skip to content

Instantly share code, notes, and snippets.

@FND
Last active November 28, 2016 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save FND/82d07ec247fb5a43d815e63c12a3cf77 to your computer and use it in GitHub Desktop.
Save FND/82d07ec247fb5a43d815e63c12a3cf77 to your computer and use it in GitHub Desktop.
custom Python module importer
from hook import register_import_hook
register_import_hook()
try:
import test_foo
print("✓ imported", test_foo.TEST_NAME, test_foo.TEST)
except Exception as err:
print("✗ import failed:", err)
try:
import test_bar
print("✓ imported", test_bar.TEST_NAME, test_bar.TEST)
except Exception as err:
print("✗ import failed:", err)
import sys
class CustomImporter:
PATH_TRIGGER = "test_"
def __init__(self, path_entry):
print("~~ INIT", path_entry)
return
def find_module(self, fullname, path=None):
print("~~ FIND", fullname, path)
mod = default_import(fullname, path) # TODO
mod.TEST = True
return mod
def register_import_hook():
sys.path_hooks.append(CustomImporter)
sys.path.insert(0, CustomImporter.PATH_TRIGGER)
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