需要使用python导入模块。

2024-06-11 23:29:01 发布

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

Google风格的python指南指出,应该: “仅对包和模块使用导入。”

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

是否有一个工具可以标记违反此建议的行为?在

派林特不这么做。例如,如下: 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')

然后,用rc文件运行pylint就可以了:

^{pr2}$

在可能的代码中搜索:http://pylint-messages.wikidot.com/all-codes,我没有看到任何类似的警告。在

我也没有在pep8或pyflakes中看到任何能抓住这个的东西。在


Tags: 模块工具httpsiogithub风格htmlexists
1条回答
网友
1楼 · 发布于 2024-06-11 23:29:01

为此,我制作了以下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))

相关问题 更多 >