Skip to content

Commit 78b9f67

Browse files
committed
[Enum] raise TypeError if super().__new__ called in custom __new__
1 parent add8d45 commit 78b9f67

File tree

4 files changed

+245
-55
lines changed

4 files changed

+245
-55
lines changed

Doc/howto/enum.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1353,6 +1353,13 @@ to handle any extra arguments::
13531353
members; it is then replaced by Enum's :meth:`__new__` which is used after
13541354
class creation for lookup of existing members.
13551355

1356+
.. warning::
1357+
1358+
*Do not* call `super().__new__()`, as the lookup-only `__new__` is the one
1359+
that is found; instead, use the data type directly -- e.g.::
1360+
1361+
obj = int.__new__(cls, value)
1362+
13561363

13571364
OrderedEnum
13581365
^^^^^^^^^^^

Lib/enum.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -856,6 +856,8 @@ def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, s
856856
value = first_enum._generate_next_value_(name, start, count, last_values[:])
857857
last_values.append(value)
858858
names.append((name, value))
859+
if names is None:
860+
names = ()
859861

860862
# Here, names is either an iterable of (name, value) or a mapping.
861863
for item in names:
@@ -1112,6 +1114,11 @@ def __new__(cls, value):
11121114
for member in cls._member_map_.values():
11131115
if member._value_ == value:
11141116
return member
1117+
# still not found -- verify that members exist, in-case somebody got here mistakenly
1118+
# (such as via super when trying to override __new__)
1119+
if not cls._member_map_:
1120+
raise TypeError("%r has no members defined" % cls)
1121+
#
11151122
# still not found -- try _missing_ hook
11161123
try:
11171124
exc = None

0 commit comments

Comments
 (0)