Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading