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

Where is the init method invoked in enum classes?

I have a class like the one below.

from enum import Enum, unique
from typing import Tuple

@unique
class Test(Enum):
    v1: Tuple = (1, "value_1")
    v2: Tuple = (2, "value_2")

    def __init__(self, value_number, value_name) -> None:
        self.value_number = value_number
        self.value_name = value_name

    @classmethod
    def get_value_name_by_value_number(cls, number: int) -> str:
        for member in cls.__members__.values():
            if member.value_number == number:
                return member.value_name
        else:
            raise NotImplementedError()

if __name__ == '__main__':
    name = Test.get_value_name_by_value_number(number=2)
    print(name)

When I run the code, the output is correct. But I don’t understand why it’s working with no problem. As far as I know the __init__ method is called on the creation of an instance. The method I’m calling is classmethod and thus I’m not creating an object and calling it directly from the class. So the __init__ is not invoked. But how does my class know what member.value_number and member.value_name are?

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 :

When creating the Test class, the Enum internals will create all enum members and manually call your __init__ method:

enum_member.__init__(*args)

You’d think it’d just instantiate your class normally somewhere, but with how much weird magic goes on in the Enum implementation, it turns out that wouldn’t work.

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