【问题标题】:Can inherited public methods be excluded from Pylint's statistics?可以从 Pylint 的统计信息中排除继承的公共方法吗?
【发布时间】:2022-01-16 02:27:33
【问题描述】:

Pylint 不断报告以下代码的错误 (R: 73,0:MyLogging: Too many public methods (22/20)):

class MyLogging(logging.Logger):

    def foo(self):
        pass

    def bar(self):
        pass

起初我认为这是 Pylint 中的一个错误,因为 MyLogging 类正好有 22 行代码,但后来我意识到,它还包括基类 logging.Logger 中的所有公共方法,它添加了20 到统计数据。

是否可以从 Pylint 统计信息中排除基类的公共方法?

PS.:我知道我可以将max-public-methods 更改为更高的数字,或者使用# pylint: disable=R0904 添加一次性例外

【问题讨论】:

    标签: python pylint


    【解决方案1】:

    有办法,但没有一个是好的。

    这是不可配置的:您可以在 Pylint 的 design_analysis.MisdesignChecker 中检查代码,在 def leave_class:

    for method in node.methods():
        if not method.name.startswith('_'):
            nb_public_methods += 1
    

    上面的代码只是简单地遍历了所有不以“_”开头的方法,并将它们算作公共方法。

    因此,我看到了两种方法来做你想做的事:

    1. fork Pylint 并修改此方法:

       for method in node.methods():
           if not method.name.startswith('_') and method.parent == node:
               nb_public_methods += 1
      

      method.parent - 定义此函数的类节点;同样在您的leave_class 函数中,您有一个参数node - 这是类节点。

      比较一下就知道是不是当前类了。

    2. 在 Pylint 配置中禁用此规则并创建您自己的插件:

       MAX_NUMBER_PUBLIC_METHODS = 3
       class PublicMethodsChecker(BaseChecker):
           __implements__ = (IASTNGChecker,)
      
           name = 'custom-public-methods-checker'
      
           msgs = {
               "C1002": ('Too many public methods (%s/%s)',
                     'Used when class has too many public methods, try to reduce \
                      this to get a more simple (and so easier to use) class.'),
           }
      
           def leave_class(self, node):
               """check number of public methods"""
               nb_public_methods = 0
               print type(node)
               for method in node.methods():
                   if not method.name.startswith('_') and method.parent == node:
                       nb_public_methods += 1
               if nb_public_methods > MAX_NUMBER_PUBLIC_METHODS:
                    self.add_message('C1002',
                                node=node,
                                args=(nb_public_methods, MAX_NUMBER_PUBLIC_METHODS))
      

      基本上,此实现是对 Pylint 源代码 design_analysis.MisdesignChecker 的稍作修改的摘录。

    有关插件的更多信息,请参阅Helping pylint to understand things it doesn't,并在 Pylint 源代码中。

    【讨论】:

    • 感谢您的回复。我暂时增加了公共方法的最大数量。我可能会实施插件的想法,当项目更成熟并且更多的开发人员会使用它时。
    • Pylint 插件部分也是一个很好的参考。 docs.pylint.org/plugins.html
    【解决方案2】:

    pylint 目前没有允许忽略父方法的配置。您可以按照 Romanl 的建议绕过问题,直到我为您的 pb 创建的问题在上游得到解决 (http://www.logilab.org/ticket/116963)

    【讨论】:

      猜你喜欢
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 2019-10-06
      • 1970-01-01
      • 2014-11-09
      • 1970-01-01
      • 2012-12-11
      相关资源
      最近更新 更多