【问题标题】:Disable pylint warning E1101 when using enums使用枚举时禁用 pylint 警告 E1101
【发布时间】:2018-07-19 17:29:10
【问题描述】:

我最近遇到了 Anthony Fox 的 this article,它展示了如何使用枚举在 django CharFields 中创建选择集,我认为这非常简洁。

基本上,您创建一个 Enum 的子类:

from enum import Enum

class ChoiceEnum(Enum):
    @classmethod
    def choices(cls):
        return tuple((x.name, x.value) for x in cls)

然后可以像这样在您的模型中使用:

from .utils import ChoiceEnum

class Car(models.Model):
    class Colors(ChoiceEnum):
        RED = 'red'
        WHITE = 'white'
        BLUE = 'blue'

    color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED.value)

red_cars = Car.objects.filter(color=Car.Colors.RED.value)

但是,每当您尝试访问枚举值 (Colors.RED.value) 时,pylint 都会引发警告

E1101:Instance of 'str' has no 'value' member

有没有办法避免/禁用 ChoiceEnum 的每个实例的此警告?

This answer 仅适用于 ChoiceEnum 的子类,不适用于 ChoiceEnum 本身。

【问题讨论】:

  • 我认为stackoverflow.com/questions/35990313/… 可能会解决您的问题
  • 我认为正确的解决方案是让 pylint 识别Enums。向他们提交增强请求/错误报告。
  • @VitorBaptista 我在我的问题中链接到该答案,它仅适用于 ChoiceEnum 的子类(并且有很多)。如果可能的话,我想要一个更全局的解决方案(除了完全禁用警告)。
  • 原来这个issue已经用pylint打开了:github.com/PyCQA/pylint/issues/533

标签: python django enums pylint


【解决方案1】:

由于issue 仍然打开,我们可以使用以下解决方法

from .utils import ChoiceEnum

class Car(models.Model):
    class Colors(ChoiceEnum, Enum):
        RED = 'red'
        WHITE = 'white'
        BLUE = 'blue'

    color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED.value)

这现在不会产生 pylint 错误

【讨论】:

  • 我花了一些时间才找到解决方案。它在 Colors 类继承中。无论如何,我无法让它工作。我想说这个问题根本与继承无关。
猜你喜欢
  • 1970-01-01
  • 2011-05-19
  • 2017-10-12
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多