]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-44524: Fix cryptic TypeError message when trying to subclass special forms in...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sat, 28 Aug 2021 18:09:45 +0000 (11:09 -0700)
committerGitHub <noreply@github.com>
Sat, 28 Aug 2021 18:09:45 +0000 (11:09 -0700)
This was a Python 3.9 regression.
(cherry picked from commit a3a4d20d6798aa2975428d51f3a4f890248810cb)

Co-authored-by: Yurii Karabas <1998uriyyo@gmail.com>
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2021-08-10-16-57-10.bpo-44524.dk9QX4.rst [new file with mode: 0644]

index 7b2fd6980899383041a794ebc21c11bf4e46a195..459af253e2ce149962c8c9e43162cbaf5fd0c0a1 100644 (file)
@@ -2418,6 +2418,22 @@ class GenericTests(BaseTestCase):
         self.assertEqual(c.from_b, 'b')
         self.assertEqual(c.from_c, 'c')
 
+    def test_subclass_special_form(self):
+        for obj in (
+            ClassVar[int],
+            Final[int],
+            Union[int, float],
+            Optional[int],
+            Literal[1, 2],
+            Concatenate[int, ParamSpec("P")],
+            TypeGuard[int],
+        ):
+            with self.subTest(msg=obj):
+                with self.assertRaisesRegex(
+                        TypeError, f'^{re.escape(f"Cannot subclass {obj!r}")}$'
+                ):
+                    class Foo(obj):
+                        pass
 
 class ClassVarTests(BaseTestCase):
 
index 423329a98005c85f7f9278f042c1afa7cf317a0b..4c2d9fc3320f34c3d647dbf77fb10a31e2f8e9ab 100644 (file)
@@ -1081,6 +1081,9 @@ class _GenericAlias(_BaseGenericAlias, _root=True):
         return operator.getitem, (origin, args)
 
     def __mro_entries__(self, bases):
+        if isinstance(self.__origin__, _SpecialForm):
+            raise TypeError(f"Cannot subclass {self!r}")
+
         if self._name:  # generic version of an ABC or built-in class
             return super().__mro_entries__(bases)
         if self.__origin__ is Generic:
diff --git a/Misc/NEWS.d/next/Library/2021-08-10-16-57-10.bpo-44524.dk9QX4.rst b/Misc/NEWS.d/next/Library/2021-08-10-16-57-10.bpo-44524.dk9QX4.rst
new file mode 100644 (file)
index 0000000..bc3659f
--- /dev/null
@@ -0,0 +1,2 @@
+Make exception message more useful when subclass from typing special form
+alias. Patch provided by Yurii Karabas.