Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions Lib/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,12 @@ def __set_name__(self, enum_class, member_name):
# This may fail if value is not hashable. We can't add the value
# to the map, and by-value lookups for this value will be
# linear.
enum_class._value2member_map_.setdefault(value, enum_member)
if value not in enum_class._hashable_values_:
value2member_map = enum_class._value2member_map_
size = len(value2member_map)
value2member_map.setdefault(value, enum_member)
# A new key can't already be in the list, so skip the linear scan.
if (len(value2member_map) != size
Comment on lines +319 to +323

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an interesting solution, but I think making _hashable_values_ a set() would be better.

or value not in enum_class._hashable_values_):
enum_class._hashable_values_.append(value)
except TypeError:
# keep track of the value in a list so containment checks are quick
Expand Down
28 changes: 28 additions & 0 deletions Lib/test/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -3530,6 +3530,34 @@ class Directions(Enum):
UNRESTRICTED = frozenset({"sc", "cs"})
self.assertIs(Directions({"sc"}), Directions.DOWN_ONLY)

def test_hashable_values_creation_work(self):
class CountedInt(int):
comparisons = 0
__hash__ = int.__hash__

def __eq__(self, other):
type(self).comparisons += 1
return super().__eq__(other)

size = 200
values = [CountedInt(i) for i in range(size)]
CountedInt.comparisons = 0
Big = Enum('Big', [(f'M{i}', v) for i, v in enumerate(values)])
self.assertLess(CountedInt.comparisons, 4 * size)
self.assertEqual(len(Big), size)
self.assertEqual(Big._hashable_values_, values)
self.assertIn(values[-1], Big)

def test_hashable_values_with_aliases(self):
class Color(Enum):
RED = 1
GREEN = 2
CRIMSON = 1
BLUE = 3
self.assertEqual(Color._hashable_values_, [1, 2, 3])
self.assertIs(Color.CRIMSON, Color.RED)
self.assertIn(1, Color)


class TestOrder(unittest.TestCase):
"test usage of the `_order_` attribute"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up creation of :class:`~enum.Enum` classes with many members: adding a
member no longer scans the list of every value added before it.
Loading