bpo-44524: Fix cryptic TypeError message when trying to subclass special forms in `typing` (GH-27710)

This was a Python 3.9 regression.
This commit is contained in:
Yurii Karabas 2021-08-18 22:08:32 +03:00 committed by GitHub
parent 6fb62b42f4
commit a3a4d20d67
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 0 deletions

View File

@ -2424,6 +2424,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):

View File

@ -1086,6 +1086,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:

View File

@ -0,0 +1,2 @@
Make exception message more useful when subclass from typing special form
alias. Patch provided by Yurii Karabas.