Last active
November 28, 2016 16:42
-
-
Save FND/82d07ec247fb5a43d815e63c12a3cf77 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 | |
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) |
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 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) |
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