Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-45417: fix quadratic behaviour when creating an enum #28907

Merged
merged 3 commits into from
Oct 14, 2021
Merged
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
21 changes: 14 additions & 7 deletions Lib/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,11 +235,18 @@ def __set_name__(self, enum_class, member_name):
enum_member._sort_order_ = len(enum_class._member_names_)
# If another member with the same value was already defined, the
# new member becomes an alias to the existing one.
for name, canonical_member in enum_class._member_map_.items():
if canonical_member._value_ == enum_member._value_:
enum_member = canonical_member
break
else:
try:
try:
# try to do a fast lookup to avoid the quadratic loop
enum_member = enum_class._value2member_map_[value]
cfbolz marked this conversation as resolved.
Show resolved Hide resolved
except TypeError:
for name, canonical_member in enum_class._member_map_.items():
if canonical_member._value_ == value:
enum_member = canonical_member
break
else:
raise KeyError
except KeyError:
# this could still be an alias if the value is multi-bit and the
# class is a flag class
if (
Expand Down Expand Up @@ -301,7 +308,7 @@ class _EnumDict(dict):
"""
def __init__(self):
super().__init__()
self._member_names = []
self._member_names = {} # use a dict to keep insertion order
self._last_values = []
self._ignore = []
self._auto_called = False
Expand Down Expand Up @@ -365,7 +372,7 @@ def __setitem__(self, key, value):
)
self._auto_called = True
value = value.value
self._member_names.append(key)
self._member_names[key] = None
self._last_values.append(value)
super().__setitem__(key, value)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix quadratic behaviour in the enum module: Creation of enum classes with a
lot of entries was quadratic.