Skip to content

Commit 81fa08c

Browse files
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 a3a4d20) Co-authored-by: Yurii Karabas <[email protected]>
1 parent cd986e9 commit 81fa08c

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

Lib/test/test_typing.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2418,6 +2418,22 @@ def __new__(cls, arg):
24182418
self.assertEqual(c.from_b, 'b')
24192419
self.assertEqual(c.from_c, 'c')
24202420

2421+
def test_subclass_special_form(self):
2422+
for obj in (
2423+
ClassVar[int],
2424+
Final[int],
2425+
Union[int, float],
2426+
Optional[int],
2427+
Literal[1, 2],
2428+
Concatenate[int, ParamSpec("P")],
2429+
TypeGuard[int],
2430+
):
2431+
with self.subTest(msg=obj):
2432+
with self.assertRaisesRegex(
2433+
TypeError, f'^{re.escape(f"Cannot subclass {obj!r}")}$'
2434+
):
2435+
class Foo(obj):
2436+
pass
24212437

24222438
class ClassVarTests(BaseTestCase):
24232439

Lib/typing.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1081,6 +1081,9 @@ def __reduce__(self):
10811081
return operator.getitem, (origin, args)
10821082

10831083
def __mro_entries__(self, bases):
1084+
if isinstance(self.__origin__, _SpecialForm):
1085+
raise TypeError(f"Cannot subclass {self!r}")
1086+
10841087
if self._name: # generic version of an ABC or built-in class
10851088
return super().__mro_entries__(bases)
10861089
if self.__origin__ is Generic:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Make exception message more useful when subclass from typing special form
2+
alias. Patch provided by Yurii Karabas.

0 commit comments

Comments
 (0)