Having pylint recognize custom module loader

江枫思渺然 提交于 2020-01-23 12:17:25

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/36359210/having-pylint-recognize-custom-module-loader

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!