Skip to main content
 首页 » 编程设计

python之让 pylint 识别自定义模块加载器

2025年04月02日1798°冷暖

我有一个自定义模块加载器,基本上可以进行一些重定向。我希望 pylint 能够识别这个自定义加载器。这是我的情况:

root/ 
    __init__.py 
    new/ 
        __init__.py 
        foo.py 
        bar.py 
    old/ 
        __init__.py 

我有很多客户导入 old.foo。我在 old/__init__.py 中编写了一个自定义加载程序,以将它们重定向到引擎盖下导入 new.foo。我如何让 pylint 识别这一点?当它检查 import old.foo 时,它会提示找不到 old.foo。这只是 pylint 的问题。我可以让客户端代码毫无问题地识别自定义加载程序。

请您参考如下方法:

来自 documentation on modules :

Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.

因此,如果我理解正确的话,您想将所有对 old 的引用重定向到 new,因此您需要做的就是替换 old 包含 old.py 的文件夹,其中包含:

__path__ = ["new"] 

然后当任何尝试导入 old.foo 时,它最终将导入 new.foo。