10000 [3.9] bpo-39728: Enum: fix duplicate `ValueError` (GH-22277) (GH-22282) · python/cpython@a9ba8ba · GitHub
[go: up one dir, main page]

Skip to content

Commit a9ba8ba

Browse files
authored
[3.9] bpo-39728: Enum: fix duplicate ValueError (GH-22277) (GH-22282)
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 4465df6 commit a9ba8ba

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
@@ -628,7 +628,7 @@ def _generate_next_value_(name, start, count, last_values):
628628

629629
@classmethod
630630
def _missing_(cls, value):
631-
raise ValueError("%r is not a valid %s" % (value, cls.__qualname__))
631+
return None
632632

633633
def __repr__(self):
634634
return "<%s.%s: %r>" % (

Lib/test/test_enum.py

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

1835+
def test_default_missing(self):
1836+
class Color(Enum):
1837+
RED = 1
1838+
GREEN = 2
1839+
BLUE = 3
1840+
try:
1841+
Color(7)
1842+
except ValueError as exc:
1843+
self.assertTrue(exc.__context__ is None)
1844+
else:
1845+
raise Exception('Exception not raised.')
1846+
18351847
def test_missing(self):
18361848
class Color(Enum):
18371849
red = 1
@@ -1850,7 +1862,12 @@ def _missing_(cls, item):
18501862
# trigger not found
18511863
return None
18521864
self.assertIs(Color('three'), Color.blue)
1853-
self.assertRaises(ValueError, Color, 7)
1865+
try:
1866+
Color(7)
1867+
except ValueError as exc:
1868+
self.assertTrue(exc.__context__ is None)
1869+
else:
1870+
raise Exception('Exception not raised.')
18541871
try:
18551872
Color('bad return')
18561873
except TypeError as exc:

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,7 @@ Marcos Donolo
432432
Dima Dorfman
433433
Yves Dorfsman
434434
Michael Dorman
435+
Andrey Doroschenko
435436
Steve Dower
436437
Allen Downey
437438
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