import sys, imp __path__ = [ '/tmp/test' ] class TestLoader(object): def __init__(self, file, filename, stuff): self.file = file self.filename = filename self.stuff = stuff def load_module(self, fullname): mod = imp.load_module(fullname, self.file, self.filename, self.stuff) if self.file: self.file.close() mod.__loader__ = self # for introspection return mod class TestImporter(object): def __init__(self, path): print('TestImporter %r\n' % path) if path not in ['/tmp/test']: raise ImportError def find_module(self, fullname, path=None): print('find_module %r %r %r\n' % ( fullname, path, __path__)) if not fullname.startswith('testimport'): return None _, mod_name = fullname.rsplit('.',1) found = imp.find_module(mod_name, path or ['/tmp/test']) print('%r\n' % (found,)) return TestLoader(*found) sys.path_hooks.insert(0,TestImporter) sys.path_importer_cache = {} import testimport.foo