Skip to content

Commit 34653bb

Browse files
authored
gh-125259: Fix error notes removal in enum initialization (GH-125647)
1 parent aaed91c commit 34653bb

File tree

3 files changed

+25
-11
lines changed

3 files changed

+25
-11
lines changed

Lib/enum.py

+5-11
Original file line numberDiff line numberDiff line change
@@ -557,22 +557,16 @@ def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **k
557557
classdict['_all_bits_'] = 0
558558
classdict['_inverted_'] = None
559559
try:
560-
exc = None
561560
classdict['_%s__in_progress' % cls] = True
562561
enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
563562
classdict['_%s__in_progress' % cls] = False
564563
delattr(enum_class, '_%s__in_progress' % cls)
565564
except Exception as e:
566-
# since 3.12 the line "Error calling __set_name__ on '_proto_member' instance ..."
567-
# is tacked on to the error instead of raising a RuntimeError
568-
# recreate the exception to discard
569-
exc = type(e)(str(e))
570-
exc.__cause__ = e.__cause__
571-
exc.__context__ = e.__context__
572-
tb = e.__traceback__
573-
if exc is not None:
574-
raise exc.with_traceback(tb)
575-
#
565+
# since 3.12 the note "Error calling __set_name__ on '_proto_member' instance ..."
566+
# is tacked on to the error instead of raising a RuntimeError, so discard it
567+
if hasattr(e, '__notes__'):
568+
del e.__notes__
569+
raise
576570
# update classdict with any changes made by __init_subclass__
577571
classdict.update(enum_class.__dict__)
578572
#

Lib/test/test_enum.py

+19
Original file line numberDiff line numberDiff line change
@@ -1888,6 +1888,25 @@ def test_wrong_inheritance_order(self):
18881888
class Wrong(Enum, str):
18891889
NotHere = 'error before this point'
18901890

1891+
def test_raise_custom_error_on_creation(self):
1892+
class InvalidRgbColorError(ValueError):
1893+
def __init__(self, r, g, b):
1894+
self.r = r
1895+
self.g = g
1896+
self.b = b
1897+
super().__init__(f'({r}, {g}, {b}) is not a valid RGB color')
1898+
1899+
with self.assertRaises(InvalidRgbColorError):
1900+
class RgbColor(Enum):
1901+
RED = (255, 0, 0)
1902+
GREEN = (0, 255, 0)
1903+
BLUE = (0, 0, 255)
1904+
INVALID = (256, 0, 0)
1905+
1906+
def __init__(self, r, g, b):
1907+
if not all(0 <= val <= 255 for val in (r, g, b)):
1908+
raise InvalidRgbColorError(r, g, b)
1909+
18911910
def test_intenum_transitivity(self):
18921911
class number(IntEnum):
18931912
one = 1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix the notes removal logic for errors thrown in enum initialization.

0 commit comments

Comments
 (0)