gh-105509: Simplify implementation of `typing.Annotated` (#105510)

This commit is contained in:
Alex Waygood 2023-09-01 21:57:25 +01:00 committed by GitHub
parent 8f9ea43ee8
commit a1cbace91b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 27 deletions

View File

@ -8189,8 +8189,7 @@ class AnnotatedTests(BaseTestCase):
def test_new(self):
with self.assertRaisesRegex(
TypeError,
'Type Annotated cannot be instantiated',
TypeError, 'Cannot instantiate typing.Annotated',
):
Annotated()

View File

@ -2001,7 +2001,8 @@ def __mro_entries__(self, bases):
return (self.__origin__,)
class Annotated:
@_SpecialForm
def Annotated(self, params):
"""Add context-specific metadata to a type.
Example: Annotated[int, runtime_check.Unsigned] indicates to the
@ -2048,14 +2049,6 @@ class Annotated:
where T1, T2 etc. are TypeVars, which would be invalid, because
only one type should be passed to Annotated.
"""
__slots__ = ()
def __new__(cls, *args, **kwargs):
raise TypeError("Type Annotated cannot be instantiated.")
@_tp_cache
def __class_getitem__(cls, params):
if not isinstance(params, tuple) or len(params) < 2:
raise TypeError("Annotated[...] should be used "
"with at least two arguments (a type and an "
@ -2068,11 +2061,6 @@ def __class_getitem__(cls, params):
metadata = tuple(params[1:])
return _AnnotatedAlias(origin, metadata)
def __init_subclass__(cls, *args, **kwargs):
raise TypeError(
"Cannot subclass {}.Annotated".format(cls.__module__)
)
def runtime_checkable(cls):
"""Mark a protocol class as a runtime protocol.

View File

@ -0,0 +1,3 @@
:data:`typing.Annotated` is now implemented as an instance of
``typing._SpecialForm`` rather than a class. This should have no user-facing
impact for users of the :mod:`typing` module public API.