Having pylint recognize custom module loader

2019-05-28 11:11发布

I have a custom module loader that basically does some redirection. I would like pylint to recognize this custom loader. This is my situation:

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

I have a lot of clients importing old.foo. I wrote a custom loader in old/__init__.py to redirect these to import new.foo under the hood. How do I get pylint to recognize this? When it lints import old.foo, it complains that it can't find old.foo. This is only a problem with pylint. I can get client code to recognize the custom loader without any issue.

标签: python pylint
2条回答
男人必须洒脱
2楼-- · 2019-05-28 11:25

You have to remember that pylint is a static analyser and as such doesn't actually load python file (except in some cases where it can't do otherwise, e.g. compiled code). As such it's not aware of custom importer or other tricks taking part of python's high dynamicity.

That being said:

  • you may still write a "brain" plugin for astroid (the library under pylint) that will help pylint understand your code's specificity

  • by relying on standard mecanism such as __path__ manipulation you'll get more chance to avoid such need, either because at some point pylint may understand this or because someone else will have contributed a plugin for that purpose.

查看更多
疯言疯语
3楼-- · 2019-05-28 11:36

from the 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.

So if I understand correctly you want to redirect any references to old to redirect to new, so all you would need to do is replace the old folder with old.py that contains this:

__path__ = ["new"]

Then when anything tries to import old.foo it will end up importing new.foo.

查看更多
登录 后发表回答