Created
March 10, 2017 12:20
-
-
Save honnix/7806840a65d64c12caa3aefb72f5009b to your computer and use it in GitHub Desktop.
python module import hook
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
import sys | |
import imp | |
class Test: | |
pass | |
class MyLoader: | |
def load_module(self, fullname): | |
try: | |
return sys.modules[fullname] | |
except KeyError: | |
pass | |
print "--- load ---" | |
print fullname | |
m = Test() | |
m.__file__ = "clr:" + fullname | |
m.__path__ = [] | |
m.__loader__ = self | |
m.__call__ = lambda : sys.stdout.write("i'm " + fullname + '\n') | |
sys.modules.setdefault(fullname, m) | |
return m | |
class MyFinder: | |
def find_module(self, fullname, path = None): | |
print "--- find ---" | |
print fullname | |
print path | |
if fullname.startswith("clr."): | |
return MyLoader() | |
return None | |
print "--- init ---" | |
__path__ = [] | |
sys.meta_path.append(MyFinder()) | |
# from clr.Foo.Bar import Baz | |
# Baz() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment