Skip to content

[3.10] bpo-44524: Fix cryptic TypeError message when trying to subclass special forms in typing (GH-27710) #27815

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand Down
3 changes: 3 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1084,6 +1084,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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Make exception message more useful when subclass from typing special form
alias. Patch provided by Yurii Karabas.