If I'm doing interactive work in Python and have an Enum
that looks like this
from enum import Enum
class UnsafeColor(Enum):
RED = 1
GREEN = 2
BLUE = 3
I may do
[In]: socks = UnsafeColor.RED
<rerun file>
[In]: shoes = UnsafeColor.RED
[In]: socks == shoes
[Out]: False
This is kind of surprising, but the problem is that rerunning the file has created a new UnsafeColor
class with members that is not equal to the old one. I can avoid this by doing something like
from functools import lru_cache
try:
get_interactive_safe_enum
except NameError as e:
@lru_cache(maxsize=None)
def get_interactive_safe_enum(*args, **kwargs):
return Enum(*args, **kwargs)
SafeColor = get_interactive_safe_enum("SafeColor", "RED GREEN BLUE")
Now the following works as expected:
[In]: hat = SafeColor.RED
<rerun file>
[In]: shirt = SafeColor.RED
[In]: hat == shirt
[Out]: True
This works, but it's not winning any awards. There appears to be lots of singleton and metaclass magic going on with Enum
, so I wonder, is there a better way to accomplish this?