Why are mutable values allowed in Python Enums? -


this of follow on why mutable values in python enums same object?.

if values of enum mutable (e.g. lists, etc.), values can changed @ time. think poses of issue if enum members retrieved value, if inadvertently changes value of enum looks up:

>>> 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] not valid color 

i think given normal python idioms okay, implication being users can use mutables enum values, understand can of worms might opening.

however brings second issue - since can enum memeber value, , value can mutable, must doing lookup means other hashmap/dict, since mutable cannot key in such dict.

wouldn't more efficient (although, granted, less flexible) limit enum values mutable types lookup-by-value implemented dict?

it appears answer second question hiding in plain sight in soure code enum.py.

each enum does contain dict of value->member pairs hashable (i.e. immutable) values, , when enum value, attempts retrieve member dict. if value not hashable, brute-force compares equality against existing enum values, returning member if finds match. relevant code in lines 468-476 in enum.py:

try:     if value in cls._value2member_map_:         return cls._value2member_map_[value] except typeerror:     # not there, long search -- o(n) behavior     member in cls._member_map_.values():         if member._value_ == value:             return member raise valueerror("%r not valid %s" % (value, cls.__name__)) 

so appears though designers of enum.py wanted have quick lookup when getting enums value, still wanted give flexibility of having mutable values enum values (even though still can't think of reason why want in first place).


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -