2017-07-11 43 views
1

python的谷歌樣式指南指出,應該: 「僅對包和模塊使用導入。」要求python導入爲模塊

https://google.github.io/styleguide/pyguide.html#Imports

是否有一個工具,它的標誌違反本建議的?

Pylint不這樣做。例如,以下內容: Is there a tool to lint Python based on the Google style guide?

創建test.py的違反準則(exists是一個函數,而不是一個模塊):

"""Test file for pylint""" 
from os.path import exists 

exists('/home') 

然後,運行pylint的與RC文件不就好了:

$ pylint --rcfile=googlecl-pylint.rc -r n -s n test.py 
$ echo $? 
0 

通過可能的代碼搜索:http://pylint-messages.wikidot.com/all-codes,我沒有看到任何看起來像它會發出警告反對這一點。

我也沒有看到pep8或pyflakes中的任何東西可以捕捉到這一點。

+3

誰做對Python編程慣例谷歌的權威?你應該堅持[PEP準則](https://www.python.org/dev/peps/pep-0008/#imports),這就是最新的。 –

+0

我也在尋找這個。任何運氣,@jobevers? – Mitar

+0

@mitar:還沒有。 – jobevers

回答

1

我給這個目的以下pylint的插件:

import astroid 
from pylint import checkers, interfaces 
from pylint.checkers import utils 


class ImportOnlyModulesChecked(checkers.BaseChecker): 
    __implements__ = interfaces.IAstroidChecker 

    name = 'import-only-modules' 
    priority = -1 
    msgs = { 
    'W5521': (
     "Import \"%s\" from \"%s\" is not a module.", 
     'import-only-modules', 
     "Only modules should be imported.", 
    ), 
    } 

    @utils.check_messages('import-only-modules') 
    def visit_importfrom(self, node): 
    try: 
     imported_module = node.do_import_module(node.modname) 
    except astroid.AstroidBuildingException: 
     # Import errors should be checked elsewhere. 
     return 

    if node.level is None: 
     modname = node.modname 
    else: 
     modname = '.' * node.level + node.modname 

    for (name, alias) in node.names: 
     # Wildcard imports should be checked elsewhere. 
     if name == '*': 
     continue 

     try: 
     imported_module.import_module(name, True) 
     # Good, we could import "name" as a module relative to the "imported_module". 
     except astroid.AstroidImportError: 
     self.add_message(
      'import-only-modules', 
      node=node, 
      args=(name, modname), 
     ) 
     except astroid.AstroidBuildingException: 
     # Some other error. 
     pass 


def register(linter): 
    linter.register_checker(ImportOnlyModulesChecked(linter))