我想确定库中每个python模块的导入,以便在自定义配置管理框架中使用。我见过像snakefood这样的工具,但我更喜欢在正常程序执行期间计算依赖图,而不是编译步骤。
到目前为止,我已尝试编写自定义Finder and Loader。这两种方法在第一次导入模块时按预期工作,但由于sys.modules
缓存,不会在后续导入时触发。
每次导入模块时,我都可以覆盖__built__.__import__
通知,但似乎这种方法不明智,因为PEP 302。
我可以在sys.modules
缓存查找前放置导入挂钩吗?或者另一种快速计算依赖关系的方法?
答案 0 :(得分:1)
重新分配给sys.modules
是可能的(如果是hacky):
import sys
import inspect
old_sys_modules = sys.modules
class NewSysModules():
def __getitem__(self, mod_name):
frame = inspect.currentframe().f_back
while frame.f_globals["__name__"].startswith("importlib"):
frame = frame.f_back # go back until we're not in a importlib frame
importer = frame.f_globals["__name__"]
print(f"importing {mod_name} from {importer}")
return old_sys_modules[mod_name]
def __setitem__(self, mod_name, module):
old_sys_modules[mod_name] = module
sys.modules = NewSysModules()
但是,如果导入系统发生更改,则可能需要进行一些维护。