from importlib import machinery import sys import types class Module(types.ModuleType): pass class LazyModule(Module): def __getattribute__(self, attr): raise RuntimeError("don't touch me!") class LazyImporter: def find_spec(self, name, path=None, target=None): if name != 'lazybits': return None return machinery.ModuleSpec(name, self) @staticmethod def create_module(spec): return Module(spec.name) @staticmethod def exec_module(module): module.__class__ = LazyModule sys.meta_path.append(LazyImporter()) import lazybits # Should not trigger the RuntimeError until after this point. try: print(lazybits.__name__) except RuntimeError: print('RuntimeError raised where expected')