[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 c95ad7a91f)

Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
This commit is contained in:
Ethan Furman 2020-09-16 17:37:51 -07:00 committed by GitHub
parent 4465df6266
commit a9ba8ba9a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 21 additions and 2 deletions

View File

@ -628,7 +628,7 @@ class Enum(metaclass=EnumMeta):
@classmethod
def _missing_(cls, value):
raise ValueError("%r is not a valid %s" % (value, cls.__qualname__))
return None
def __repr__(self):
return "<%s.%s: %r>" % (

View File

@ -1832,6 +1832,18 @@ class TestEnum(unittest.TestCase):
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
@ -1850,7 +1862,12 @@ class TestEnum(unittest.TestCase):
# 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:

View File

@ -432,6 +432,7 @@ Marcos Donolo
Dima Dorfman
Yves Dorfsman
Michael Dorman
Andrey Doroschenko
Steve Dower
Allen Downey
Cesar Douady

View File

@ -0,0 +1 @@
fix default `_missing_` so a duplicate `ValueError` is not set as the `__context__` of the original `ValueError`