Is defining classmethods in Enum classes bad practice or not?

I have Enum class:

class Group(StrEnum):
  admin = 'admin'
  manager = 'manager'
  user = 'user'

  @classmethod
  def get_staff_groups(cls):
    return {cls.admin, cls.manager}

  @classmethod
  def get_user_groups(cls):
    return {cls.user}

Is it good practice or not?

I tried like written above. Can Enum contains methods?

>Solution :

Here is the Python doc about the differences between Enum classes and normal ones: https://docs.python.org/3/howto/enum.html#enum-class-differences. Some of the given examples even contain a classmethod:

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7
    #
    @classmethod
    def from_date(cls, date):
        return cls(date.isoweekday())

What you need to ask yourself is, basically, "does my method serve the purpose of my class?" If the answer is "yes", then sure: the class can contain it.

Leave a Reply