]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.8] bpo-39728: Enum: fix duplicate `ValueError` (GH-22277) (GH-22283)
authorEthan Furman <ethan@stoneleaf.us>
Thu, 17 Sep 2020 00:38:14 +0000 (17:38 -0700)
committerGitHub <noreply@github.com>
Thu, 17 Sep 2020 00:38:14 +0000 (17:38 -0700)
fix default `_missing_` to return `None` instead of raising a `ValueError`
Co-authored-by: Andrey Darascheka <andrei.daraschenka@leverx.com>.
(cherry picked from commit c95ad7a91fbd7636f33a098d3b39964ab083bf49)

Co-authored-by: Ethan Furman <ethan@stoneleaf.us>
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 c2adfd1c6c0bb72beb298aab85ecae78bf302b71..de9ed4c1ec371129c80ea0392c3dc093b87c603c 100644 (file)
@@ -634,7 +634,7 @@ class Enum(metaclass=EnumMeta):
 
     @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>" % (
index daa44ae6824ce0e59b1737212d6df4e57d30e570..745962a1e66fe9770ab6ed62a0a4b0a6e1a24cc8 100644 (file)
@@ -1834,6 +1834,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
@@ -1852,7 +1864,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 e6d0c3ba1270864c7680d6f745dfd9fdaeb453f3..eee6b9accaa50f8f6fbf464c63570907d360d1ac 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -421,6 +421,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`