Skip to content

Commit d0b2fa4

Browse files
[3.12] gh-125259: Fix error notes removal in enum initialization (GH-125647) (GH-125953)
(cherry picked from commit 34653bb) Co-authored-by: Mario Šaško <[email protected]>
1 parent f6682fb commit d0b2fa4

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
@@ -592,19 +592,13 @@ def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **k
592592
classdict['_all_bits_'] = 0
593593
classdict['_inverted_'] = None
594594
try:
595-
exc = None
596595
enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
597596
except Exception as e:
598-
# since 3.12 the line "Error calling __set_name__ on '_proto_member' instance ..."
599-
# is tacked on to the error instead of raising a RuntimeError
600-
# recreate the exception to discard
601-
exc = type(e)(str(e))
602-
exc.__cause__ = e.__cause__
603-
exc.__context__ = e.__context__
604-
tb = e.__traceback__
605-
if exc is not None:
606-
raise exc.with_traceback(tb)
607-
#
597+
# since 3.12 the note "Error calling __set_name__ on '_proto_member' instance ..."
598+
# is tacked on to the error instead of raising a RuntimeError, so discard it
599+
if hasattr(e, '__notes__'):
600+
del e.__notes__
601+
raise
608602
# update classdict with any changes made by __init_subclass__
609603
classdict.update(enum_class.__dict__)
610604
#

Lib/test/test_enum.py

+19
Original file line numberDiff line numberDiff line change
@@ -1852,6 +1852,25 @@ def test_wrong_inheritance_order(self):
18521852
class Wrong(Enum, str):
18531853
NotHere = 'error before this point'
18541854

1855+
def test_raise_custom_error_on_creation(self):
1856+
class InvalidRgbColorError(ValueError):
1857+
def __init__(self, r, g, b):
1858+
self.r = r
1859+
self.g = g
1860+
self.b = b
1861+
super().__init__(f'({r}, {g}, {b}) is not a valid RGB color')
1862+
1863+
with self.assertRaises(InvalidRgbColorError):
1864+
class RgbColor(Enum):
1865+
RED = (255, 0, 0)
1866+
GREEN = (0, 255, 0)
1867+
BLUE = (0, 0, 255)
1868+
INVALID = (256, 0, 0)
1869+
1870+
def __init__(self, r, g, b):
1871+
if not all(0 <= val <= 255 for val in (r, g, b)):
1872+
raise InvalidRgbColorError(r, g, b)
1873+
18551874
def test_intenum_transitivity(self):
18561875
class number(IntEnum):
18571876
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)