From c95ad7a91fbd7636f33a098d3b39964ab083bf49 Mon Sep 17 00:00:00 2001 From: Ethan Furman Date: Wed, 16 Sep 2020 10:26:50 -0700 Subject: [PATCH] bpo-39728: Enum: fix duplicate `ValueError` (GH-22277) fix default `_missing_` to return `None` instead of raising a `ValueError` Co-authored-by: Andrey Darascheka --- Lib/enum.py | 2 +- Lib/test/test_enum.py | 19 ++++++++++++++++++- Misc/ACKS | 1 + .../2020-02-24-10-58-34.bpo-39728.kOOaHn.rst | 1 + 4 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2020-02-24-10-58-34.bpo-39728.kOOaHn.rst diff --git a/Lib/enum.py b/Lib/enum.py index 0c2cf569fac..060b2a0dadf 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -629,7 +629,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.__qualname__)) + return None def __repr__(self): return "<%s.%s: %r>" % ( diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py index 2fcd047989a..5d72d82cec2 100644 --- a/Lib/test/test_enum.py +++ b/Lib/test/test_enum.py @@ -1845,6 +1845,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 @@ -1863,7 +1875,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: diff --git a/Misc/ACKS b/Misc/ACKS index 8b0d7a45da1..2628d6b690d 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -433,6 +433,7 @@ Marcos Donolo Dima Dorfman Yves Dorfsman Michael Dorman +Andrey Doroschenko Steve Dower Allen Downey Cesar Douady diff --git a/Misc/NEWS.d/next/Library/2020-02-24-10-58-34.bpo-39728.kOOaHn.rst b/Misc/NEWS.d/next/Library/2020-02-24-10-58-34.bpo-39728.kOOaHn.rst new file mode 100644 index 00000000000..beb2016a85b --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-02-24-10-58-34.bpo-39728.kOOaHn.rst @@ -0,0 +1 @@ +fix default `_missing_` so a duplicate `ValueError` is not set as the `__context__` of the original `ValueError`