]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-39728: Enum: fix duplicate `ValueError` (GH-22277)
authorEthan Furman <ethan@stoneleaf.us>
Wed, 16 Sep 2020 17:26:50 +0000 (10:26 -0700)
committerGitHub <noreply@github.com>
Wed, 16 Sep 2020 17:26:50 +0000 (10:26 -0700)
fix default `_missing_` to return `None` instead of raising a `ValueError`
Co-authored-by: Andrey Darascheka <andrei.daraschenka@leverx.com>
Lib/enum.py
Lib/test/test_enum.py
Misc/ACKS
Misc/NEWS.d/next/Library/2020-02-24-10-58-34.bpo-39728.kOOaHn.rst [new file with mode: 0644]

index 0c2cf569fac88d924308713ce6a743e4f95ebeac..060b2a0dadf4576cf200599c10b3ca56d76368b3 100644 (file)
@@ -629,7 +629,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>" % (
index 2fcd047989afb2099023299f0b19f0e04da3518c..5d72d82cec27ffe53ee363b917886d9625e13d63 100644 (file)
@@ -1845,6 +1845,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
@@ -1863,7 +1875,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:
index 8b0d7a45da16953e7cdd993a37035376a99811da..2628d6b690d1cbe8a57d21e057029e87759c808e 100644 (file)
--- 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 (file)
index 0000000..beb2016
--- /dev/null
@@ -0,0 +1 @@
+fix default `_missing_` so a duplicate `ValueError` is not set as the `__context__` of the original `ValueError`