3

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

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.

现在,当我的客户开始使用新功能时,皮林特惊恐地跳上跳下。

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 规则吗?还有其他解决方案吗?

4

3 回答 3

6

这是我的解决方案,灵感来自于Yoni H回答中提供 的ActiveState 食谱食谱中的示例。

在 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 对这个错误保持沉默。

ps 你可以抱怨这段代码不是很漂亮。我同意这个观点。但我认为它对客户的好处超过了它的代码味道。

于 2010-08-18T18:13:45.183 回答
2

根据您的评论,既然您要使用枚举类型,为什么不看看这个 SO question这个 ActiveState 食谱食谱

出于个人喜好,我会选择将枚举类型添加到类中,就像SO question中的答案之一(为了上下文而无耻地复制):

class Animal:
   def __init__(self, name):
       self.name = name

   def __str__(self):
       return self.name

   def __repr__(self):
       return "<Animal: %s>" % self

Animal.DOG = Animal("dog")
Animal.CAT = Animal("cat")
于 2010-08-18T08:12:52.483 回答
0

务实地说,为什么要假设 pylint(或任何 lint)应该保持沉默?鉴于误报和误报之间存在偏差,lints 应该更喜欢前者。在我看来,因为 Pylint 将其结果表示为人们认为应该最大化的分数,但没有“获胜”奖。

另一方面,它抱怨的结构肯定是丑陋的。我知道为了方便起见,server_api 被简化了,但是你真的需要对模块命名空间进行处理吗?从您的客户端代码看来,current_count方法名称是硬编码的,为什么不在服务器中?

于 2010-08-18T07:11:41.603 回答