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 行代码,但后来我意识到,它包括基类 中的所有公共(public)方法logging.Logger
同样,它在统计中增加了 20。
是否可以从 Pylint 统计信息中排除基类的公共(public)方法?
PS.: 我知道我可以将 max-public-methods
更改为更大的数字,或者使用 # pylint: disable=R0904
添加一次性异常>
最佳答案
方法有很多,但都不好。
这是不可配置的:您可以在 def leave_class
中检查 Pylint 的 design_analysis.MisdesignChecker 中的代码:
for method in node.methods():
if not method.name.startswith('_'):
nb_public_methods += 1
上面的代码简单地遍历了所有不以“_”开头的方法,并将它们计为公共(public)方法。
因此,我看到有两种方法可以做您想做的事:
派生 Pylint 并修改此方法:
for method in node.methods(): if not method.name.startswith('_') and method.parent == node: nb_public_methods += 1
method.parent
- 定义此函数的类节点;同样在您的leave_class
函数中,您有一个参数node
- 这是类节点。对比一下就知道是不是当前类了。
在 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 源代码中。
关于python - 继承的公共(public)方法是否可以从 Pylint 的统计数据中排除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339042/