Repository navigation
typing.Annotated[int, ...] is subclassable #96771
Description
Activity
- addedtype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
on Sep 12, 2022 Related: #96080
This PR introduced explicit__mro_entries__to_AnnotatedAlias.But,
Annotatedwas subclassable even in3.10.0:Python 3.10.0 (default, Nov 1 2021, 10:24:06) [Clang 11.0.0 (clang-1100.0.33.16)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import typing >>> class Some(typing.Annotated[int, 'meta']): ... ... >>> Some.__mro__ (<class '__main__.Some'>, <class 'int'>, <class 'object'>)
Looks like there's a test for quite the opposite: https://github.com/python/cpython/blame/53a54b781d1f05f2d0b40ce88b3da92d5d23e9d2/Lib/test/test_typing.py#L6713-L6717
It ensures that
Annotatedcan be subclassed. Related: #27841I disagree that it is a bug that you can subclass
Annotated[int, ...]. I think you're meant to be able to useAnnotated[int, ...]at runtime at all sites where you could useint. Why should code like this be disallowed?SpecialInt: TypeAlias = Annotated[int, "very special"] class Foo(SpecialInt): ...
This works fine, and I don't see why the cases should be treated differently:
SpecialInt: TypeAlias = int class Foo(SpecialInt): ...
In any case, it would surely be backwards-incompatible to change this behaviour now?
Yes, changing this will be backward incompatible. Even type-checkers can understand this:
from typing import Annotated class Some(Annotated[int, 'meta']): pass reveal_type(Some) # ex.py:6: note: Revealed type is "Overload(def (Union[builtins.str, builtins.bytes, array.array[Any], mmap.mmap, ctypes._CData, pickle.PickleBuffer, typing.SupportsInt, typing_extensions.SupportsIndex, _typeshed.SupportsTrunc] =) -> ex.Some, def (Union[builtins.str, builtins.bytes], base: typing_extensions.SupportsIndex) -> ex.Some)"
So, it probably should stay as-is.
Reacted by Alex Waygood
You can subclass
Annotated[int, "meta"]:But, here are a couple of problems:
Annotatedin the first placeAnnotatedcannot be subclassed: https://github.com/python/cpython/blame/53a54b781d1f05f2d0b40ce88b3da92d5d23e9d2/Lib/test/test_typing.py#L6562-L6565 hereI think that
Annotatedshould not be subclasses and this is a bug.The PR is incoming :)
I found this while working on #96769