[Python-checkins] bpo-44524: Fix cryptic TypeError message when trying to subclass special forms in `typing` (GH-27710)
miss-islington
webhook-mailer at python.org
Sat Aug 28 14:09:49 EDT 2021
https://github.com/python/cpython/commit/81fa08c5ea2cf15254b951034b9d6c7358f96d79
commit: 81fa08c5ea2cf15254b951034b9d6c7358f96d79
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2021-08-28T11:09:45-07:00
summary:
bpo-44524: Fix cryptic TypeError message when trying to subclass special forms in `typing` (GH-27710)
This was a Python 3.9 regression.
(cherry picked from commit a3a4d20d6798aa2975428d51f3a4f890248810cb)
Co-authored-by: Yurii Karabas <1998uriyyo at gmail.com>
files:
A Misc/NEWS.d/next/Library/2021-08-10-16-57-10.bpo-44524.dk9QX4.rst
M Lib/test/test_typing.py
M Lib/typing.py
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index 7b2fd698089938..459af253e2ce14 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -2418,6 +2418,22 @@ def __new__(cls, arg):
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):
diff --git a/Lib/typing.py b/Lib/typing.py
index 423329a98005c8..4c2d9fc3320f34 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -1081,6 +1081,9 @@ def __reduce__(self):
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
index 00000000000000..bc3659fca52098
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-08-10-16-57-10.bpo-44524.dk9QX4.rst
@@ -0,0 +1,2 @@
+Make exception message more useful when subclass from typing special form
+alias. Patch provided by Yurii Karabas.
More information about the Python-checkins
mailing list