17

I recently came across this article by Anthony Fox which shows how to use enums to create the choice set in django CharFields, which I thought was pretty neat.

Basically, you create a subclass of Enum:

from enum import Enum

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

Which can then be used in your models like so:

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)

However, pylint throws a warning whenever you try to access the enum value (Colors.RED.value)

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

Is there a way to avoid / disable this warning for every instance of ChoiceEnum?

This answer only works on the subclass of ChoiceEnum, not ChoiceEnum itself.

cmasri
  • 461
  • 1
  • 5
  • 12
  • I think https://stackoverflow.com/questions/35990313/avoid-pylint-warning-e1101-instance-of-has-no-member-for-class-with-dyn?noredirect=1&lq=1 might solve your issue – Vitor Baptista Jul 19 '18 at 18:29
  • 3
    I think the proper solution is for pylint to recognize `Enum`s. File an enhancement request/bug report with them. – Ethan Furman Jul 19 '18 at 19:05
  • @VitorBaptista I linked to that answer in my question, it only works on subclasses of ChoiceEnum (and there are a lot of them). If possible, I'd like a more global solution (other than disabling the warning entirely). – cmasri Jul 20 '18 at 00:06
  • 1
    Turns out this issue has already been opened with pylint: https://github.com/PyCQA/pylint/issues/533 – cmasri Jul 24 '18 at 15:50

1 Answers1

2

Since the issue is still open, we can use the following workaround

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)

This doesn't create the pylint error now

newbie
  • 1,282
  • 3
  • 20
  • 43
  • It took me some time to find the solution. It's in the Colors class inheritance. Anyway, I couldn't make it work. I'd say the problem is not related with the inheritance at all. – Guto Marrara Marzagao Oct 10 '20 at 16:50