Pylint:可以从统计中排除继承的公共方法吗?

时间:2013-01-15 13:41:06

标签: python pylint

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添加一次例外

2 个答案:

答案 0 :(得分:6)

有一些方法,但没有一个是好的。

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

     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的略微修改的摘录。

有关插件的更多信息:http://www.logilab.org/blogentry/78354,以及pylint源代码。

答案 1 :(得分:2)

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