Skip to content

[3.12] gh-125259: Fix error notes removal in enum initialization (GH-125647) #125953

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

Merged
merged 2 commits into from
Oct 25, 2024
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
16 changes: 5 additions & 11 deletions Lib/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,19 +592,13 @@ def __new__(metacls, cls, bases, classdict, *, boundary=None, _simple=False, **k
classdict['_all_bits_'] = 0
classdict['_inverted_'] = None
try:
exc = None
enum_class = super().__new__(metacls, cls, bases, classdict, **kwds)
except Exception as e:
# since 3.12 the line "Error calling __set_name__ on '_proto_member' instance ..."
# is tacked on to the error instead of raising a RuntimeError
# recreate the exception to discard
exc = type(e)(str(e))
exc.__cause__ = e.__cause__
exc.__context__ = e.__context__
tb = e.__traceback__
if exc is not None:
raise exc.with_traceback(tb)
#
# since 3.12 the note "Error calling __set_name__ on '_proto_member' instance ..."
# is tacked on to the error instead of raising a RuntimeError, so discard it
if hasattr(e, '__notes__'):
del e.__notes__
raise
# update classdict with any changes made by __init_subclass__
classdict.update(enum_class.__dict__)
#
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -1852,6 +1852,25 @@ def test_wrong_inheritance_order(self):
class Wrong(Enum, str):
NotHere = 'error before this point'

def test_raise_custom_error_on_creation(self):
class InvalidRgbColorError(ValueError):
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
super().__init__(f'({r}, {g}, {b}) is not a valid RGB color')

with self.assertRaises(InvalidRgbColorError):
class RgbColor(Enum):
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
INVALID = (256, 0, 0)

def __init__(self, r, g, b):
if not all(0 <= val <= 255 for val in (r, g, b)):
raise InvalidRgbColorError(r, g, b)

def test_intenum_transitivity(self):
class number(IntEnum):
one = 1
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix the notes removal logic for errors thrown in enum initialization.
Loading