This is somewhat of a follow on to Why are mutable values in Python Enums the same object?.
If the values of an Enum
are mutable (e.g. list
s, etc.), those values can be changed at any time. I think this poses something of an issue if Enum
members are retrieved by value, especially if someone inadvertently changes the value of an Enum
he looks up:
>>> from enum import Enum
>>> class Color(Enum):
black = [1,2]
blue = [1,2,3]
>>> val_1 = [1,2]
>>> val_2 = [1,2,3]
>>> Color(val_1)
<Color.black: [1, 2]>
>>> Color(val_2)
<Color.blue: [1, 2, 3]>
>>> my_color = Color(val_1)
>>> my_color.value.append(3)
>>> Color(val_2)
<Color.black: [1, 2, 3]>
>>> Color(val_1)
Traceback (most recent call last):
...
ValueError: [1, 2] is not a valid Color
I think given normal Python idioms this is okay, with the implication being that users can use mutables as their Enum
values, but just to understand the can of worms they might be opening.
However this brings up a second issue - since you can look up an Enum
memeber by value, and the value can be mutable, it must be doing the lookup by a means other than a hashmap/dict
, since the mutable cannot be a key
in such a dict
.
Wouldn't it be more efficient (although, granted, less flexible) to limit Enum
values to only immutable types so that lookup-by-value could be implemented with a dict
?