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

Any fancy way to unwind Enum classes in python?

I am currently coding a package that contains several Enum classes and would like to use the symbolic names directly from the package name, not from the classes themselves, as OpenCV does. Is there anyway to define the classes but still accessing their symbolic names directly from the package or shall I directly hardcode them in the package’s __init__.py ?

For now I am currently in this state:

from enum import Enum

class enum_class1(Enum):
    class1_sym1: int = 0
    class1_sym2: int = 1
    class1_sym3: int = 2

class enum_class2(Enum):
    class2_sym1: int = 0
    class2_sym2: int = 1
    class2_sym3: int = 2

What I am currently doing :

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

import mypackage as p

state = p.enum_class2.class_2_sim1

What I would like to rather do :

import mypackage as p

state = p.class_2_sim1

>Solution :

At the risk of compromising static analysis, you can automatically define global variables for each Enum member (as suggested in Barmar’s answer) by taking advantage of the Enum.__members__ mapping. Given

class enum_class1(Enum):
    class1_sym1: int = 0
    class1_sym2: int = 1
    class1_sym3: int = 2

we have

>>> enum_class1.__members__
mappingproxy({'class1_sym1': <enum_class1.class1_sym1: 0>,
              'class1_sym2': <enum_class1.class1_sym2: 1>,
              'class1_sym3': <enum_class1.class1_sym3: 2>})

This mapping can be used to populate the module’s globals as

globals().update(enum_class1.__members__)

So,

class enum_class1(Enum):
    class1_sym1: int = 0
    class1_sym2: int = 1
    class1_sym3: int = 2

globals().update(enum_class1.__members__)

print(repr(class1_sym1))

works as expected, and will print

<enum_class1.class1_sym1: 0>
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