Find this solution.
It requires 2 modules:
"""module2 module : wrapper to modify object"""
import sys
import importlib
_hackers = []
def register(obj):
_hackers.append(obj)
class Hacker:
def hack(self, module):
return module
class Loader:
def __init__(self):
self.module = None
def find_module(self, name, path):
sys.meta_path.remove(self)
self.module = importlib.import_module(name)
sys.meta_path.insert(0, self)
return self
def load_module(self, name):
if not self.module:
raise ImportError("Unable to load module.")
module = self.module
for hacker in _hackers:
module = hacker.hack(module)
sys.modules[name] = module
return module
sys.meta_path.insert(0, Loader())
"""decorations module"""
import types
import module2
_modules = {}
_decorators = []
def register(decorator, modules=None):
"""Register a decorator for a list of module names."""
if not decorator:
return
if not modules and decorator in _decorators:
return
if not modules:
_decorators.append(decorator)
return
if isinstance(modules, str):
modules = (modules,)
for module in modules:
if module not in _modules:
_modules[module] = []
_modules[module].append(decorator)
class One(module2.Hacker):
def hack(self, module):
for decorator in _modules.get(module.__name__, ()):
self.decorate(module, decorator)
for decorator in _decorators:
self.decorate(module, decorator)
return module
def decorate(self, module, decorator):
for attr in module.__dict__:
obj = getattr(module, attr)
if isinstance(obj, types.FunctionType):
setattr(module, attr, decorator(obj))
module2.register(One())
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…