Skip to content

Commit

Permalink
[3.8] bpo-39728: Enum: fix duplicate ValueError (GH-22277) (GH-22283)
Browse files Browse the repository at this point in the history
fix default `_missing_` to return `None` instead of raising a `ValueError`
Co-authored-by: Andrey Darascheka <[email protected]>.
(cherry picked from commit c95ad7a)

Co-authored-by: Ethan Furman <[email protected]>
  • Loading branch information
ethanfurman committed Sep 17, 2020
1 parent 007edda commit 5efb1a7
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Lib/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ def _generate_next_value_(name, start, count, last_values):

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

def __repr__(self):
return "<%s.%s: %r>" % (
Expand Down
19 changes: 18 additions & 1 deletion Lib/test/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -1834,6 +1834,18 @@ class Dupes(Enum):
third = auto()
self.assertEqual([Dupes.first, Dupes.second, Dupes.third], list(Dupes))

def test_default_missing(self):
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
try:
Color(7)
except ValueError as exc:
self.assertTrue(exc.__context__ is None)
else:
raise Exception('Exception not raised.')

def test_missing(self):
class Color(Enum):
red = 1
Expand All @@ -1852,7 +1864,12 @@ def _missing_(cls, item):
# trigger not found
return None
self.assertIs(Color('three'), Color.blue)
self.assertRaises(ValueError, Color, 7)
try:
Color(7)
except ValueError as exc:
self.assertTrue(exc.__context__ is None)
else:
raise Exception('Exception not raised.')
try:
Color('bad return')
except TypeError as exc:
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,7 @@ Marcos Donolo
Dima Dorfman
Yves Dorfsman
Michael Dorman
Andrey Doroschenko
Steve Dower
Allen Downey
Cesar Douady
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
fix default `_missing_` so a duplicate `ValueError` is not set as the `__context__` of the original `ValueError`

0 comments on commit 5efb1a7

Please sign in to comment.