How to live with enum and enum34?

I noticed a different enumeration behavior in Python.

I was initially surprised to notice that the output for this was int :

 >>>import enum >>>class Color(enum.Enum): red = 1 >>>Color.red 1 

Then I realized that instead of enum34 , enum installed:

 $ sudo apt-get install python-enum34 

And now the result is different:

 >>>Color.red <Color.red: 1> 

My current application accepts enum types, where I get the enum value with value.value . Of course, this will throw an exception if an incorrect enum is set.

How can I deal with this problem?

+6
source share
2 answers

It is believed that it looks like you had an enum package that existed before 3.4 Enum. enum34 is named so because the previous package already exists.

Both enum and enum34 are installed in the same place, so their joint existence is not easy - plus this will make your code difficult to distribute, since one of the enumerations will be in a non-standard location.

One of the possibilities is to use virtual envs - then you can set which enumeration is necessary for the application in venv .

+4
source

Adapting @ Jerry101's comment in another answer, here is what I got:

 def is_using_enum34(self): try: import enum return enum.__file__.__str__().endswith("__init__.pyc") except: return False return False 

I noticed that for:
enum34: enum.__file__ == __init__.pyc
enum: enum.__file__ == enum.pyc .

I have not used this heavily, and it is probably not perfect, but it is suitable for what I am looking at and may be useful to others.

0
source

All Articles