Skip to content
Open
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
30 changes: 30 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -9943,6 +9943,36 @@ def test_cannot_subclass(self):
class C(Annotated):
pass

def test_subclass(self):
# gh-89132: subclassing an annotated type is the same as subclassing
# the annotated type itself.
class MyGeneric(Generic[T]):
pass

for tp in (list, List, List[int], list[int], MyGeneric[int],
collections.abc.Sequence[int]):
with self.subTest(tp=tp):
class C(Annotated[tp, "a decoration"]):
pass

class D(tp):
pass

self.assertEqual(C.__bases__, D.__bases__)
self.assertEqual(C.__mro__[1:], D.__mro__[1:])

def test_cannot_subclass_not_subclassable(self):
# gh-89132: the error message is the same as for the annotated type.
for tp in (Union[int, str], int | str, T):
with self.subTest(tp=tp):
with self.assertRaises(TypeError) as cm:
class D(tp):
pass
with self.assertRaises(TypeError) as cm2:
class C(Annotated[tp, "a decoration"]):
pass
self.assertEqual(str(cm2.exception), str(cm.exception))

def test_cannot_check_instance(self):
with self.assertRaises(TypeError):
isinstance(5, Annotated[int, "positive"])
Expand Down
9 changes: 8 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2254,7 +2254,14 @@ def __getattr__(self, attr):
return super().__getattr__(attr)

def __mro_entries__(self, bases):
return (self.__origin__,)
origin = self.__origin__
if not isinstance(origin, type):
# The origin can need a resolution itself, e.g. list[int].
meth = getattr(origin, '__mro_entries__', None)
if meth is not None:
bases = tuple(origin if b is self else b for b in bases)
return meth(bases)
return (origin,)


@_TypedCacheSpecialForm
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Subclassing :data:`typing.Annotated` types now works if the annotated type
is a generic alias, e.g. ``Annotated[list[int], "metadata"]``. If the
annotated type cannot be subclassed, the raised error is now the same as for
that type.
Loading