如何在第一次导入时修补python3模块?

2024-06-16 10:10:15 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想动态地修补tkinter.Tk,使windows保持领先。如果我确定下面的代码确实使用了Tkinter,那么我可以在其余代码之前import tkinter并执行必要的更新。在

但是如何设置按需修补模块,即只有当其余代码真正导入模块时?在

我知道sys.path_hooks和{},但我希望有更简单的方法。我不想更改查找或加载机制,我只想在将导入的模块对象传递到导入模块之前获得它。在

我不需要支持Python 3.5以前的版本。在


Tags: 模块path对象方法代码importtkinterwindows
1条回答
网友
1楼 · 发布于 2024-06-16 10:10:15

我选择了包装^{}

This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement

import builtins
original_import = builtins.__import__

def custom_import(*args, **kw):
    module = original_import(*args, **kw)

    if (module.__name__ == "interesting_module" 
        and not getattr(module, "patch_is_performed", False)):
        patch(module)
        module.patch_is_performed = True

    return module

builtins.__import__ = custom_import

相关问题 更多 >