python – API可以告诉Pylint不要在客户端代码中抱怨吗?

我在可重用的类中有一些代码可以修改某些类型.这是一个简化版本.

class Foo:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1

# Add another method outside of the class definition.
# Pylint doesn't care about this, and rates this file 10/10.

Foo.__dict__["current_count"] = lambda self: self.count

在实际代码中,“current_count”是一个变量,而不是一个固定的字符串,这就是为什么我没有写:

Foo.current_count = lambda self: self.count # Cannot do in my scenario.

现在,当我的客户来使用新功能时,Pylint惊恐地跳起来.

import server_api

def main():
    foo_count = server_api.Foo()
    foo_count.increment()


    print foo_count.current_count()
    # Pylint complains here:
    #     E1101:  8:main: Instance of 'Foo' has no 'current_count' member
    # I don't want to have to tell pylint to disable that message in every client.

main()

每个使用这个新函数的类都受到惩罚,我被迫在每个引用中禁用该消息.我会在API中添加一些代码,告诉Pylint在这个类上有未知的引用时会发冷.

唉,pylint文件是……嗯…不是有利于我的理解的质量,我一直无法在那里找到任何建议.

将其煮沸:我可以告诉我的API代码中的pylint关闭与此类相关的E1101规则,只要客户端引用它吗?还有其他解决方案吗?

最佳答案 这是我的解决方案,灵感来自于
ActiveState cookbook recipe
answer中提供的
ActiveState cookbook recipe中的示例.

对于Foo类,我添加了这个无用的__getattr__方法.

def __getattr__(self, name):
    # This is only called when the normal mechanism fails, so in practice should never be called.
    # It is only provided to satisfy pylint that it is okay not to raise E1101 errors in the client code.
    raise AttributeError("%r instance has no attribute %r" % (self, name))

这应该与以前的版本几乎无法区分.它不应该在正常的事件过程中被调用,但它足以说服pylint对此错误保持安静.

附:你可以抱怨这段代码不是很漂亮.我赞同这个意见.但我认为它对客户的好处超过了它的代码味道.

点赞