From fad6e371937147fc6bf6efed45c707690ed080f9 Mon Sep 17 00:00:00 2001 From: Yurii Karabas <1998uriyyo@gmail.com> Date: Tue, 10 Aug 2021 16:58:06 +0300 Subject: [PATCH] Make exc msg more useful when subclass from special form --- Lib/test/test_typing.py | 16 ++++++++++++++++ Lib/typing.py | 3 +++ .../2021-08-10-16-57-10.bpo-44524.dk9QX4.rst | 2 ++ 3 files changed, 21 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2021-08-10-16-57-10.bpo-44524.dk9QX4.rst diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 06141f8bbcb614..d090c5f8818da1 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -2424,6 +2424,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 51468aeaf5b755..eeeb295b6c2c21 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -1086,6 +1086,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.