8000 [3.8] bpo-39728: Enum: fix duplicate `ValueError` (GH-22277) · ethanfurman/cpython@53fbe5a · GitHub
[go: up one dir, main page]

Skip to content

Commit 53fbe5a

Browse files
committed
[3.8] bpo-39728: Enum: fix duplicate ValueError (pythonGH-22277)
fix default `_missing_` to return `None` instead of raising a `ValueError` Co-authored-by: Andrey Darascheka <andrei.daraschenka@leverx.com>. (cherry picked from commit c95ad7a) Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
1 parent 3f40121 commit 53fbe5a

File tree

4 files changed

+21
-2
lines changed

4 files changed

+21
-2
lines changed

Lib/enum.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,7 @@ def _generate_next_value_(name, start, count, last_values):
634634

635635
@classmethod
636636
def _missing_(cls, value):
637-
raise ValueError("%r is not a valid %s" % (value, cls.__name__))
637+
return None
638638

639639
def __repr__(self):
640640
return "<%s.%s: %r>" % (

Lib/test/test_enum.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1823,6 +1823,18 @@ class Dupes(Enum):
18231823
third = auto()
18241824
self.assertEqual([Dupes.first, Dupes.second, Dupes.third], list(Dupes))
18251825

1826+
def test_default_missing(self):
1827+
class Color(Enum):
1828+
RED = 1
1829+
GREEN = 2
1830+
BLUE = 3
1831+
try:
1832+
Color(7)
1833+
except ValueError as exc:
1834+
self.assertTrue(exc.__context__ is None)
1835+
else:
1836+
raise Exception('Exception not raised.')
1837+
18261838
def test_missing(self):
18271839
class Color(Enum):
18281840
red = 1
@@ -1841,7 +1853,12 @@ def _missing_(cls, item):
18411853
# trigger not found
18421854
return None
18431855
self.assertIs(Color('three'), Color.blue)
1844-
self.assertRaises(ValueError, Color, 7)
1856+
try:
1857+
Color(7)
1858+
except ValueError as exc:
1859+
self.assertTrue(exc.__context__ is None)
1860+
else:
1861+
raise Exception('Exception not raised.')
18451862
try:
18461863
Color('bad return')
18471864
except TypeError as exc:

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,7 @@ Marcos Donolo
421421
Dima Dorfman
422422
Yves Dorfsman
423423
Michael Dorman
424+
Andrey Doroschenko
424425
Steve Dower
425426
Allen Downey
426427
Cesar Douady
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
fix default `_missing_` so a duplicate `ValueError` is not set as the `__context__` of the original `ValueError`

0 commit comments

Comments
 (0)
0