Is defining classmethods in Enum classes bad practice or not?

I have Enum class:

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

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

  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: Some of the given examples even contain a classmethod:

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7
    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