3

I defined an enum class and would like to be able to use its attributes without need to access it through class name. I mean:

class MyEnum:
    ONE = 1
    TWO = 2
    ...

if MyEnum.ONE == 1:
    "Typic use"
if TWO == 2:
    "My desire"

Is there a way to do this?


In my specific context, I'm calculating points externality of a window through Cohen–Sutherland algorithm, so I have the following code:

class Externality:
    INSIDE = 0
    LEFT = 1
    RIGTH = 2
    BELLOW = 4
    ABOVE = 8
# And at some point:
((x, y), externality) = actual

if not Externality.INSIDE in externality:
    del cohen_sutherland_list[0]

So, the needed of express Enum's name to access its items make the if statement (and the whole code) a little more verbose and redundant.

artu-hnrq
  • 1,343
  • 1
  • 8
  • 30
  • 2
    Why would you want to do this? You should use `MyEnum.TWO`. – Jaideep Shekhar Dec 21 '19 at 15:04
  • It's basically to improve readability, since in the archive context I use it the meaning of its items are pretty obvious and, in the algorithms, the name is used to define the variables that store this values is the same Emun name, so it gets a little redundant – artu-hnrq Dec 21 '19 at 15:24
  • 1
    "... the name is used to define the variables that store this values is the same Emun name" Could you please post some code for context? I am not sure what you are trying to do. – Jaideep Shekhar Dec 21 '19 at 15:31
  • I included my specific context description in the question – artu-hnrq Dec 21 '19 at 15:43
  • 1
    Too late! Drat. You have got an answer. :-) In addition, [this post is an interesting read](https://stackoverflow.com/questions/2682745/how-do-i-create-a-constant-in-python). – Jaideep Shekhar Dec 21 '19 at 15:48

1 Answers1

2

First things first: inherit from Enum.


Like everything in Python, all you need to do is assign the names:

from enum import Enum

class MyEnum(Enum):
    ONE = 1
    TWO = 2

ONE = MyEnum.ONE
TWO = MyEnum.TWO

That can get annoying fast, so a helper function would be nice:

def export_enum(enum_cls, env):
    for member in enum_cls:
        env[member.name] = member

and in use:

>>> export_enum(MyEnum, globals())
>>> TWO
<MyEnum.TWO: 2>

If you use aenum1 the export() function is already available, and can be used as a decorator:

from aenum import Enum, export

@export(globals())
class MyEnum(Enum):
    ONE = 1
    TWO = 2

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237