From 1bc7379d4f3dcc612bdd24d5760d6fde7c8ad1b4 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Sun, 29 Nov 2026 18:22:14 +0000 Subject: [PATCH] Remove compatibility code for Python versions older than 3.10 --- .github/workflows/third_party.yml | 6 +- CONTRIBUTING.md | 6 +- doc/index.rst | 109 +++++++-------- src/test_typing_extensions.py | 112 +++++---------- src/typing_extensions.py | 225 ++++++------------------------ 5 files changed, 136 insertions(+), 322 deletions(-) diff --git a/.github/workflows/third_party.yml b/.github/workflows/third_party.yml index 37a76ba9..d5a0c193 100644 --- a/.github/workflows/third_party.yml +++ b/.github/workflows/third_party.yml @@ -208,7 +208,7 @@ jobs: strategy: fail-fast: false matrix: - # 3.9 is no longer supported. 3.14 fails some tests as of 2 November 2025 + # 3.14 fails some tests as of 2 November 2025 python-version: ["3.10", "3.11", "3.12", "3.13"] runs-on: ubuntu-latest timeout-minutes: 60 @@ -401,10 +401,6 @@ jobs: - name: Run litestar tests with typing_extensions main branch working-directory: litestar run: | - # litestar's python-requires means uv won't let us add typing-extensions-latest - # as a requirement unless we do this - sed -i 's/^requires-python = ">=3.8/requires-python = ">=3.10/' pyproject.toml - uv add --editable ../typing-extensions-latest uv sync diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3e84cc5c..8fecc384 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,9 +4,9 @@ contributors need to sign the PSF Contributor Agreement. # typing\_extensions The `typing_extensions` module provides a way to access new features from the standard -library `typing` module in older versions of Python. For example, Python 3.10 adds -`typing.TypeGuard`, but users of older versions of Python can use `typing_extensions` to -use `TypeGuard` in their code even if they are unable to upgrade to Python 3.10. +library `typing` module in older versions of Python. For example, Python 3.13 adds +`typing.TypeIs`, but users of older versions of Python can use `typing_extensions` to +use `TypeIs` in their code even if they are unable to upgrade to Python 3.13. If you contribute the runtime implementation of a new `typing` feature to CPython, you are encouraged to also implement the feature in `typing_extensions`. Because the runtime diff --git a/doc/index.rst b/doc/index.rst index 25785a58..ecff5b05 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -28,8 +28,8 @@ including those that have always been present in the module. This allows users t import names from ``typing_extensions`` without having to remember exactly when each object was added to :py:mod:`typing`. There are a few exceptions: :py:class:`typing.ByteString`, which is deprecated and due to be removed in Python -3.14, is not re-exported. Similarly, the ``typing.io`` and ``typing.re`` submodules, -which are removed in Python 3.13, are excluded. +3.17, is not re-exported. Similarly, the ``typing.io`` and ``typing.re`` submodules, +which were removed in Python 3.13, are excluded. Versioning and backwards compatibility -------------------------------------- @@ -276,7 +276,7 @@ Python version in which each feature was added to :py:mod:`typing` and the - 4.6.0 - :pep:`695` * - :data:`TypeForm` - - + - 3.15 - 4.13.0 - :pep:`747` * - :data:`TypeGuard` @@ -335,14 +335,6 @@ on specific Python versions. Special typing primitives ~~~~~~~~~~~~~~~~~~~~~~~~~ -.. data:: Annotated - - See :py:data:`typing.Annotated` and :pep:`593`. In ``typing`` since 3.9. - - .. versionchanged:: 4.1.0 - - ``Annotated`` can now wrap :data:`ClassVar` and :data:`Final`. - .. data:: Any See :py:data:`typing.Any`. @@ -358,12 +350,8 @@ Special typing primitives See :py:data:`typing.Concatenate` and :pep:`612`. In ``typing`` since 3.10. - The backport does not support certain operations involving ``...`` as - a parameter; see :issue:`48` and :pr:`481` for details. - -.. data:: Final - - See :py:data:`typing.Final` and :pep:`591`. In ``typing`` since 3.8. + On Python 3.10, ``typing_extensions.Concatenate`` backports support for + ``...`` as the last argument. .. data:: Literal @@ -426,8 +414,8 @@ Special typing primitives See :py:class:`typing.NewType`. In ``typing`` since 3.5.2. - Instances of ``NewType`` were made picklable in 3.10 and an error message was - improved in 3.11; ``typing_extensions`` backports these changes. + On Python 3.10, ``typing_extensions.NewType`` backports the improved error + message from Python 3.11 for attempts to subclass a ``NewType`` instance. .. versionchanged:: 4.6.0 @@ -460,11 +448,6 @@ Special typing primitives The ``typing_extensions`` version adds support for the ``default=`` argument from :pep:`696`. - On older Python versions, ``typing_extensions.ParamSpec`` may not work - correctly with introspection tools like :func:`get_args` and - :func:`get_origin`. Certain special cases in user-defined - :py:class:`typing.Generic`\ s are also not available (e.g., see :issue:`126`). - .. versionchanged:: 4.4.0 Added support for the ``default=`` argument. @@ -497,12 +480,6 @@ Special typing primitives The ``infer_variance``, ``covariant``, and ``contravariant`` arguments are now officially supported and their validation is improved. -.. class:: ParamSpecArgs - ParamSpecKwargs - - See :py:class:`typing.ParamSpecArgs` and :py:class:`typing.ParamSpecKwargs`. - In ``typing`` since 3.10. - .. class:: Protocol See :py:class:`typing.Protocol` and :pep:`544`. In ``typing`` since 3.8. @@ -551,10 +528,6 @@ Special typing primitives .. versionadded:: 4.0.0 -.. data:: TypeAlias - - See :py:data:`typing.TypeAlias` and :pep:`613`. In ``typing`` since 3.10. - .. class:: TypeAliasType(name, value, *, type_params=()) See :py:class:`typing.TypeAliasType` and :pep:`695`. In ``typing`` since 3.12. @@ -563,14 +536,11 @@ Special typing primitives .. data:: TypeForm - See :pep:`747`. A special form representing the value of a type expression. + See :py:data:`typing.TypeForm` and :pep:`747`. In ``typing`` since 3.15. + A special form representing the value of a type expression. .. versionadded:: 4.13.0 -.. data:: TypeGuard - - See :py:data:`typing.TypeGuard` and :pep:`647`. In ``typing`` since 3.10. - .. data:: TypeIs See :py:data:`typing.TypeIs` and :pep:`742`. In ``typing`` since 3.13. @@ -588,9 +558,9 @@ Special typing primitives Features backported by ``typing_extensions`` include: - * :py:class:`typing.TypedDict` does not store runtime information about which - (if any) keys are non-required in Python 3.8, and does not honor the - *total* keyword with old-style ``TypedDict()`` on Python 3.9.0 and 3.9.1. + * :py:class:`typing.TypedDict` ignores :data:`Required` and :data:`NotRequired` + when computing :py:attr:`~typing.TypedDict.__required_keys__` and + :py:attr:`~typing.TypedDict.__optional_keys__` on Python <3.11. * :py:class:`typing.TypedDict` does not support multiple inheritance with :py:class:`typing.Generic` on Python <3.11 * :py:class:`typing.TypedDict` classes do not consistently have the @@ -789,7 +759,7 @@ Special typing primitives ``typing_extensions`` backports this change. Generic type aliases involving ``Unpack`` may not work correctly on - Python 3.10 and lower; see :issue:`103` for details. + Python 3.10; see :issue:`103` for details. .. versionadded:: 4.1.0 @@ -1003,7 +973,8 @@ Functions but unlike that method, :func:`!evaluate_forward_ref` also: * Recursively evaluates forward references nested within the type hint. - However, the amount of recursion is limited in Python 3.8 and 3.10. + On Python 3.10, string references nested in built-in generic aliases + such as ``list['str']`` can remain unresolved. * Raises :exc:`TypeError` when it encounters certain objects that are not valid type hints. * Replaces type hints that evaluate to :const:`!None` with @@ -1055,22 +1026,6 @@ Functions .. versionadded:: 4.13.0 -.. function:: get_args(tp) - - See :py:func:`typing.get_args`. In ``typing`` since 3.8. - - This function was changed in 3.9 and 3.10 to deal with :data:`Annotated` - and :class:`ParamSpec` correctly; ``typing_extensions`` backports these - fixes. - -.. function:: get_origin(tp) - - See :py:func:`typing.get_origin`. In ``typing`` since 3.8. - - This function was changed in 3.9 and 3.10 to deal with :data:`Annotated` - and :class:`ParamSpec` correctly; ``typing_extensions`` backports these - fixes. - .. function:: get_original_bases(cls) See :py:func:`types.get_original_bases`. Added to the standard library @@ -1332,6 +1287,14 @@ versions of Python, but all are listed here for completeness. .. versionadded:: 4.7.0 +.. data:: Annotated + + See :py:data:`typing.Annotated` and :pep:`593`. In ``typing`` since 3.9. + + .. versionchanged:: 4.1.0 + + ``Annotated`` can now wrap :data:`ClassVar` and :data:`Final`. + .. data:: AnyStr See :py:data:`typing.AnyStr`. @@ -1430,6 +1393,10 @@ versions of Python, but all are listed here for completeness. .. versionadded:: 4.7.0 +.. data:: Final + + See :py:data:`typing.Final` and :pep:`591`. In ``typing`` since 3.8. + .. class:: ForwardRef See :py:class:`typing.ForwardRef`. @@ -1551,6 +1518,12 @@ versions of Python, but all are listed here for completeness. See :py:class:`typing.OrderedDict`. In ``typing`` since 3.7.2. +.. class:: ParamSpecArgs + ParamSpecKwargs + + See :py:class:`typing.ParamSpecArgs` and :py:class:`typing.ParamSpecKwargs`. + In ``typing`` since 3.10. + .. class:: Pattern See :py:class:`typing.Pattern`. @@ -1601,10 +1574,18 @@ versions of Python, but all are listed here for completeness. See :py:class:`typing.Type`. In ``typing`` since 3.5.2. +.. data:: TypeAlias + + See :py:data:`typing.TypeAlias` and :pep:`613`. In ``typing`` since 3.10. + .. data:: TYPE_CHECKING See :py:data:`typing.TYPE_CHECKING`. In ``typing`` since 3.5.2. +.. data:: TypeGuard + + See :py:data:`typing.TypeGuard` and :pep:`647`. In ``typing`` since 3.10. + .. data:: Union See :py:class:`typing.Union`. @@ -1623,6 +1604,14 @@ versions of Python, but all are listed here for completeness. .. versionadded:: 4.7.0 +.. function:: get_args(tp) + + See :py:func:`typing.get_args`. In ``typing`` since 3.8. + +.. function:: get_origin(tp) + + See :py:func:`typing.get_origin`. In ``typing`` since 3.8. + .. decorator:: no_type_check See :py:func:`typing.no_type_check`. diff --git a/src/test_typing_extensions.py b/src/test_typing_extensions.py index 2675ed78..8cd7fc72 100644 --- a/src/test_typing_extensions.py +++ b/src/test_typing_extensions.py @@ -23,6 +23,7 @@ from collections import defaultdict from functools import lru_cache from pathlib import Path +from types import NoneType from unittest import TestCase, main, skipIf, skipUnless from unittest.mock import patch @@ -107,7 +108,6 @@ type_repr, ) -NoneType = type(None) T = TypeVar("T") KT = TypeVar("KT") VT = TypeVar("VT") @@ -152,7 +152,7 @@ skip_if_py313_beta_1 = skipIf( sys.version_info[:5] == (3, 13, 0, 'beta', 1), - "Bugfixes will be released in 3.13.0b2" + "Fixed in 3.13.0b2" ) ANN_MODULE_SOURCE = '''\ @@ -557,10 +557,7 @@ class NoReturnTests(BottomTypeTestsMixin, BaseTestCase): bottom_type = NoReturn def test_repr(self): - if hasattr(typing, 'NoReturn'): - self.assertEqual(repr(NoReturn), 'typing.NoReturn') - else: - self.assertEqual(repr(NoReturn), 'typing_extensions.NoReturn') + self.assertEqual(repr(NoReturn), 'typing.NoReturn') def test_get_type_hints(self): def some(arg: NoReturn) -> NoReturn: ... @@ -1063,15 +1060,11 @@ def test_basics(self): ClassVar[int][str] def test_repr(self): - if hasattr(typing, 'ClassVar'): - mod_name = 'typing' - else: - mod_name = 'typing_extensions' - self.assertEqual(repr(ClassVar), mod_name + '.ClassVar') + self.assertEqual(repr(ClassVar), 'typing.ClassVar') cv = ClassVar[int] - self.assertEqual(repr(cv), mod_name + '.ClassVar[int]') + self.assertEqual(repr(cv), 'typing.ClassVar[int]') cv = ClassVar[Employee] - self.assertEqual(repr(cv), mod_name + f'.ClassVar[{__name__}.Employee]') + self.assertEqual(repr(cv), f'typing.ClassVar[{__name__}.Employee]') def test_cannot_subclass(self): with self.assertRaises(TypeError): @@ -3286,7 +3279,7 @@ class HasNothingButSlots: self.assertIsInstance(HasNothingButSlots(), HasX) - def test_protocols_isinstance_py36(self): + def test_protocols_isinstance_with_annotated_members(self): class APoint: def __init__(self, x, y, label): self.x = x @@ -4356,7 +4349,7 @@ def test_typeddict_errors(self): with self.assertRaises(TypeError): TypedDict('Hi', [('x', int)], y=int) - def test_py36_class_syntax_usage(self): + def test_class_syntax_usage(self): self.assertEqual(LabelPoint2D.__name__, 'LabelPoint2D') self.assertEqual(LabelPoint2D.__module__, __name__) self.assertEqual(LabelPoint2D.__annotations__, {'x': int, 'y': int, 'label': str}) @@ -4761,8 +4754,7 @@ class NewGeneric[T](TypedDict): # The TypedDict constructor is not itself a TypedDict self.assertIs(is_typeddict(TypedDict), False) - if hasattr(typing, "TypedDict"): - self.assertIs(is_typeddict(typing.TypedDict), False) + self.assertIs(is_typeddict(typing.TypedDict), False) def test_is_typeddict_against_typeddict_from_typing(self): Point = typing.TypedDict('Point', {'x': int, 'y': int}) @@ -5429,17 +5421,13 @@ def test_typeddict_non_str_typename(self): class AnnotatedTests(BaseTestCase): def test_repr(self): - if hasattr(typing, 'Annotated'): - mod_name = 'typing' - else: - mod_name = "typing_extensions" self.assertEqual( repr(Annotated[int, 4, 5]), - mod_name + ".Annotated[int, 4, 5]" + "typing.Annotated[int, 4, 5]" ) self.assertEqual( repr(Annotated[List[int], 4, 5]), - mod_name + ".Annotated[typing.List[int], 4, 5]" + "typing.Annotated[typing.List[int], 4, 5]" ) def test_flatten(self): @@ -5747,11 +5735,11 @@ class MultipleGenericBases(GenericParent[int], GenericParent[float]): class TypeAliasTests(BaseTestCase): def test_canonical_usage_with_variable_annotation(self): - ns = {} - exec('Alias: TypeAlias = Employee', globals(), ns) + class Namespace: + Alias: TypeAlias = Employee - def test_canonical_usage_with_type_comment(self): - Alias: TypeAlias = Employee # noqa: F841 + self.assertIs(Namespace.Alias, Employee) + self.assertIs(Namespace.__annotations__["Alias"], TypeAlias) def test_cannot_instantiate(self): with self.assertRaises(TypeError): @@ -5778,10 +5766,7 @@ class D(type(TypeAlias)): pass def test_repr(self): - if hasattr(typing, 'TypeAlias'): - self.assertEqual(repr(TypeAlias), 'typing.TypeAlias') - else: - self.assertEqual(repr(TypeAlias), 'typing_extensions.TypeAlias') + self.assertEqual(repr(TypeAlias), 'typing.TypeAlias') def test_cannot_subscript(self): with self.assertRaises(TypeError): @@ -5813,7 +5798,7 @@ def test_repr(self): # On other versions we use typing.ParamSpec, but it is not aware of # infer_variance=. Not worth creating our own version of ParamSpec # for this. - if hasattr(typing, 'TypeAliasType') or not hasattr(typing, 'ParamSpec'): + if hasattr(typing, 'TypeAliasType'): self.assertEqual(repr(P_infer), 'P_infer') else: self.assertEqual(repr(P_infer), '~P_infer') @@ -5846,24 +5831,21 @@ def test_valid_uses(self): self.assertEqual(C2.__parameters__, (P, T)) # Test collections.abc.Callable too. - # Note: no tests for Callable.__parameters__ here - # because types.GenericAlias Callable is hardcoded to search - # for tp_name "TypeVar" in C. This was changed in 3.10. C3 = collections.abc.Callable[P, int] self.assertEqual(C3.__args__, (P, int)) + self.assertEqual(C3.__parameters__, (P,)) C4 = collections.abc.Callable[P, T] self.assertEqual(C4.__args__, (P, T)) + self.assertEqual(C4.__parameters__, (P, T)) # ParamSpec instances should also have args and kwargs attributes. - # Note: not in dir(P) because of __class__ hacks self.assertTrue(hasattr(P, 'args')) self.assertTrue(hasattr(P, 'kwargs')) - @skipIf((3, 10, 0) <= sys.version_info[:3] <= (3, 10, 2), "Needs https://github.com/python/cpython/issues/90834.") + @skipIf(sys.version_info < (3, 10, 3), "Needs https://github.com/python/cpython/issues/90834.") def test_args_kwargs(self): P = ParamSpec('P') P_2 = ParamSpec('P_2') - # Note: not in dir(P) because of __class__ hacks self.assertTrue(hasattr(P, 'args')) self.assertTrue(hasattr(P, 'kwargs')) self.assertIsInstance(P.args, ParamSpecArgs) @@ -5905,18 +5887,20 @@ class Y(Protocol[T, P]): self.assertEqual(G3.__args__, (int, Concatenate[int, ...])) self.assertEqual(G3.__parameters__, ()) + G4 = klass[int, [int, bool]] + self.assertEqual(G4.__args__, (int, (int, bool))) + self.assertEqual(G4.__parameters__, ()) + + G5 = klass[int, ...] + self.assertEqual(G5.__args__, (int, ...)) + self.assertEqual(G5.__parameters__, ()) + with self.assertRaisesRegex( TypeError, f"Too few arguments for {klass}" ): klass[int] - # The following are some valid uses cases in PEP 612 that don't work: - # These do not work in 3.9, _type_check blocks the list and ellipsis. - # G3 = X[int, [int, bool]] - # G4 = X[int, ...] - # G5 = Z[[int, str, bool]] - def test_single_argument_generic(self): P = ParamSpec("P") T = TypeVar("T") @@ -5930,6 +5914,10 @@ class ProtoZ(Protocol[P]): for klass in Z, ProtoZ: with self.subTest(klass=klass.__name__): + G5 = klass[[int, str, bool]] + self.assertEqual(G5.__args__, ((int, str, bool),)) + self.assertEqual(G5.__parameters__, ()) + G6 = klass[int, str, T] self.assertEqual(G6.__args__[0], (int, str, T)) self.assertEqual(G6.__parameters__, (T,)) @@ -5950,15 +5938,6 @@ class ProtoZ(Protocol[P]): G10 = klass[int, Concatenate[str, P]] self.assertEqual(G10.__args__[0], (int, Concatenate[str, P], )) - def test_is_param_expr(self): - P = ParamSpec("P") - P_typing = typing.ParamSpec("P_typing") - self.assertTrue(typing_extensions._is_param_expr(P)) - self.assertTrue(typing_extensions._is_param_expr(P_typing)) - if hasattr(typing, "_is_param_expr"): - self.assertTrue(typing._is_param_expr(P)) - self.assertTrue(typing._is_param_expr(P_typing)) - def test_single_argument_generic_with_parameter_expressions(self): P = ParamSpec("P") T = TypeVar("T") @@ -6253,16 +6232,6 @@ def test_substitution(self): C3 = Concatenate[str, T, P] self.assertEqual(C3[int, [bool]], (str, int, bool)) - def test_is_param_expr(self): - P = ParamSpec('P') - concat = Concatenate[str, P] - typing_concat = typing.Concatenate[str, P] - self.assertTrue(typing_extensions._is_param_expr(concat)) - self.assertTrue(typing_extensions._is_param_expr(typing_concat)) - if hasattr(typing, "_is_param_expr"): - self.assertTrue(typing._is_param_expr(concat)) - self.assertTrue(typing._is_param_expr(typing_concat)) - def test_isinstance_results_unaffected_by_presence_of_tracing_function(self): # See https://github.com/python/typing_extensions/issues/661 @@ -6313,17 +6282,13 @@ def foo(arg) -> TypeGuard[int]: ... self.assertEqual(gth(foo), {'return': TypeGuard[int]}) def test_repr(self): - if hasattr(typing, 'TypeGuard'): - mod_name = 'typing' - else: - mod_name = 'typing_extensions' - self.assertEqual(repr(TypeGuard), f'{mod_name}.TypeGuard') + self.assertEqual(repr(TypeGuard), 'typing.TypeGuard') cv = TypeGuard[int] - self.assertEqual(repr(cv), f'{mod_name}.TypeGuard[int]') + self.assertEqual(repr(cv), 'typing.TypeGuard[int]') cv = TypeGuard[Employee] - self.assertEqual(repr(cv), f'{mod_name}.TypeGuard[{__name__}.Employee]') + self.assertEqual(repr(cv), f'typing.TypeGuard[{__name__}.Employee]') cv = TypeGuard[Tuple[int]] - self.assertEqual(repr(cv), f'{mod_name}.TypeGuard[typing.Tuple[int]]') + self.assertEqual(repr(cv), 'typing.TypeGuard[typing.Tuple[int]]') def test_cannot_subclass(self): with self.assertRaises(TypeError): @@ -7063,7 +7028,7 @@ def test_drop_in_for_typing(self): te_all = set(typing_extensions.__all__) exceptions = {"ByteString"} self.assertGreaterEqual(te_all, t_all - exceptions) - # Deprecated, to be removed in 3.14 + # Deprecated, to be removed in 3.17 self.assertFalse(hasattr(typing_extensions, "ByteString")) # These were never included in `typing.__all__`, # and have been removed in Python 3.13 @@ -7332,7 +7297,7 @@ class Y(Generic[T], NamedTuple): with self.assertRaisesRegex(TypeError, 'Too many arguments'): G[int, str] - def test_non_generic_subscript_py39_plus(self): + def test_non_generic_subscript(self): # For backward compatibility, subscription works # on arbitrary NamedTuple types. class Group(NamedTuple): @@ -9459,7 +9424,6 @@ class Gen[Tx]: Gen = ns["Gen"] # owner=None, type_params=None - # NOTE: The behavior of owner=None might change in the future when ForwardRef.__owner__ is available with self.assertRaises(NameError): evaluate_forward_ref(typing.ForwardRef("Tx")) with self.assertRaises(NameError): diff --git a/src/typing_extensions.py b/src/typing_extensions.py index 6923c1bc..3240e198 100644 --- a/src/typing_extensions.py +++ b/src/typing_extensions.py @@ -456,20 +456,16 @@ def _flatten_literal_params(parameters): params.append(p) return tuple(params) - def _value_and_type_iter(params): - for p in params: - yield p, type(p) - class _LiteralGenericAlias(typing._GenericAlias, _root=True): def __eq__(self, other): if not isinstance(other, _LiteralGenericAlias): return NotImplemented - these_args_deduped = set(_value_and_type_iter(self.__args__)) - other_args_deduped = set(_value_and_type_iter(other.__args__)) + these_args_deduped = set(typing._value_and_type_iter(self.__args__)) + other_args_deduped = set(typing._value_and_type_iter(other.__args__)) return these_args_deduped == other_args_deduped def __hash__(self): - return hash(frozenset(_value_and_type_iter(self.__args__))) + return hash(frozenset(typing._value_and_type_iter(self.__args__))) class _LiteralForm(_ExtensionsSpecialForm, _root=True): def __init__(self, doc: str): @@ -482,22 +478,12 @@ def __getitem__(self, parameters): parameters = _flatten_literal_params(parameters) - val_type_pairs = list(_value_and_type_iter(parameters)) + val_type_pairs = list(typing._value_and_type_iter(parameters)) try: - deduped_pairs = set(val_type_pairs) + parameters = tuple(p for p, _ in typing._deduplicate(val_type_pairs)) except TypeError: # unhashable parameters pass - else: - # similar logic to typing._deduplicate on Python 3.9+ - if len(deduped_pairs) < len(val_type_pairs): - new_parameters = [] - for pair in val_type_pairs: - if pair in deduped_pairs: - new_parameters.append(pair[0]) - deduped_pairs.remove(pair) - assert not deduped_pairs, deduped_pairs - parameters = tuple(new_parameters) return _LiteralGenericAlias(self, parameters) @@ -647,12 +633,11 @@ def __getitem__(self, params): ) return self.copy_with(params) - _NoneType = type(None) Generator = _SpecialGenericAlias( - collections.abc.Generator, 3, defaults=(_NoneType, _NoneType) + collections.abc.Generator, 3, defaults=(_types.NoneType, _types.NoneType) ) AsyncGenerator = _SpecialGenericAlias( - collections.abc.AsyncGenerator, 2, defaults=(_NoneType,) + collections.abc.AsyncGenerator, 2, defaults=(_types.NoneType,) ) ContextManager = _SpecialGenericAlias( contextlib.AbstractContextManager, @@ -1114,13 +1099,11 @@ def __reduce__(self): del SingletonMeta -# Update this to something like >=3.13.0b1 if and when +# Update this to a `sys.version_info` check or similar if and when # PEP 764 is implemented in CPython _PEP_764_IMPLEMENTED = False if _PEP_764_IMPLEMENTED: - # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" - # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 # The standard library TypedDict below Python 3.11 does not store runtime # information about optional and required keys when using Required or NotRequired. # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. @@ -1525,10 +1508,10 @@ def greet(name: str) -> None: if hasattr(typing, "ReadOnly"): # 3.13+ get_type_hints = typing.get_type_hints -else: # <=3.13 +else: # <=3.12 # replaces _strip_annotations() def _strip_extras(t): - """Strips Annotated, Required and NotRequired from a given type.""" + """Strips Annotated, Required, NotRequired and ReadOnly from a given type.""" if isinstance(t, typing._AnnotatedAlias): return _strip_extras(t.__origin__) if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly): @@ -1555,9 +1538,8 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False): """Return type hints for an object. This is often the same as obj.__annotations__, but it handles - forward references encoded as string literals, adds Optional[t] if a - default value equal to None is set and recursively replaces all - 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' + forward references encoded as string literals and recursively replaces + 'Annotated[T, ...]', 'Required[T]', 'NotRequired[T]' and 'ReadOnly[T]' with 'T' (unless 'include_extras=True'). The argument may be a module, class, method, or function. The annotations @@ -1593,14 +1575,12 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False): return hint return {k: _strip_extras(t) for k, t in hint.items()} - _NoneType = type(None) - def _could_be_inserted_optional(t): """detects Union[..., None] pattern""" if not isinstance(t, typing._UnionGenericAlias): return False # Assume if last argument is not None they are user defined - if t.__args__[-1] is not _NoneType: + if t.__args__[-1] is not _types.NoneType: return False return True @@ -1625,7 +1605,7 @@ def _clean_optional(obj, hints, globalns=None, localns=None): original_value = original_hints[name] # value=NoneType should have caused a skip above but check for safety if original_value is None: - original_value = _NoneType + original_value = _types.NoneType # Forward reference if isinstance(original_value, str): if globalns is None: @@ -1734,10 +1714,7 @@ def __init_subclass__(cls) -> None: if _PEP_696_IMPLEMENTED: from typing import ParamSpec - -# 3.10+ else: - # Add default parameter - PEP 696 class ParamSpec(metaclass=_TypeVarLikeMeta): """Parameter specification.""" @@ -1748,7 +1725,7 @@ def __new__(cls, name, *, bound=None, covariant=False, contravariant=False, infer_variance=False, default=NoDefault): if hasattr(typing, "TypeAliasType"): - # PEP 695 implemented, can pass infer_variance to typing.TypeVar + # PEP 695 implemented, can pass `infer_variance` to `typing.ParamSpec` paramspec = typing.ParamSpec(name, bound=bound, covariant=covariant, contravariant=contravariant, @@ -1785,11 +1762,11 @@ def __init_subclass__(cls) -> None: raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") -_ConcatenateGenericAlias = typing._ConcatenateGenericAlias - -# 3.10 -if sys.version_info < (3, 11): - +# Python 3.11 added support for ellipsis in `Concatenate`. +# Breakpoint: https://github.com/python/cpython/pull/30969 +if sys.version_info >= (3, 11): + Concatenate = typing.Concatenate +else: class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True): # needed for checks in collections.abc.Callable to accept this class __module__ = "typing" @@ -1807,42 +1784,9 @@ def copy_with(self, params): def __getitem__(self, args): value = super().__getitem__(args) if isinstance(value, tuple) and any(_is_unpack(t) for t in value): - return tuple(_unpack_args(*(n for n in value))) + return tuple(_unpack_args(*value)) return value - -# <=3.10 -def _create_concatenate_alias(origin, parameters): - if sys.version_info >= (3, 10, 3): - return _ConcatenateGenericAlias(origin, parameters, - _typevar_types=(TypeVar, ParamSpec), - _paramspec_tvars=True) - else: - return _ConcatenateGenericAlias(origin, parameters) - - -# <=3.10 -@typing._tp_cache -def _concatenate_getitem(self, parameters): - if parameters == (): - raise TypeError("Cannot take a Concatenate of no types.") - if not isinstance(parameters, tuple): - parameters = (parameters,) - if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)): - raise TypeError("The last parameter to Concatenate should be a " - "ParamSpec variable or ellipsis.") - msg = "Concatenate[arg, ...]: each arg must be a type." - parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]), - parameters[-1]) - return _create_concatenate_alias(self, parameters) - - -# 3.11+; Concatenate does not accept ellipsis in 3.10 -# Breakpoint: https://github.com/python/cpython/pull/30969 -if sys.version_info >= (3, 11): - Concatenate = typing.Concatenate -# <=3.10 -else: @_ExtensionsSpecialForm def Concatenate(self, parameters): """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a @@ -1855,7 +1799,22 @@ def Concatenate(self, parameters): See PEP 612 for detailed information. """ - return _concatenate_getitem(self, parameters) + if parameters == (): + raise TypeError("Cannot take a Concatenate of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + msg = "Concatenate[arg, ...]: each arg must be a type." + parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]), + parameters[-1]) + if sys.version_info >= (3, 10, 3): + return _ConcatenateGenericAlias( + self, parameters, + _typevar_types=(TypeVar, ParamSpec), _paramspec_tvars=True + ) + return _ConcatenateGenericAlias(self, parameters) TypeGuard = typing.TypeGuard @@ -1908,7 +1867,7 @@ def f(val: Union[int, Awaitable[int]]) -> int: return typing._GenericAlias(self, (item,)) -# 3.15+? +# 3.15+ if hasattr(typing, 'TypeForm'): TypeForm = typing.TypeForm # <=3.14 @@ -2698,19 +2657,6 @@ def wrapper(*args, **kwargs): ) -def _is_param_expr(arg): - return arg is ... or isinstance( - arg, - ( - tuple, - list, - ParamSpec, - _ConcatenateGenericAlias, - typing._ConcatenateGenericAlias, - ), - ) - - # We have to do some monkey patching to deal with the dual nature of # Unpack/TypeVarTuple: # - We want Unpack to be a kind of TypeVar so it gets accepted in @@ -2718,74 +2664,25 @@ def _is_param_expr(arg): # - We want it to *not* be treated as a TypeVar for the purposes of # counting generic parameters, so that when we subscript a generic, # the runtime doesn't try to substitute the Unpack with the subscripted type. -if not hasattr(typing, "TypeVarTuple"): - def _check_generic(cls, parameters, elen=_marker): +if not _PEP_696_IMPLEMENTED: + def _check_generic(cls, parameters, elen): """Check correct count for parameters of a generic cls (internal helper). This gives a nice error message in case of count mismatch. """ - # If substituting a single ParamSpec with multiple arguments - # we do not check the count - if (inspect.isclass(cls) and issubclass(cls, typing.Generic) - and len(cls.__parameters__) == 1 - and isinstance(cls.__parameters__[0], ParamSpec) - and parameters - and not _is_param_expr(parameters[0]) - ): - # Generic modifies parameters variable, but here we cannot do this - return - if not elen: raise TypeError(f"{cls} is not a generic class") - if elen is _marker: - if not hasattr(cls, "__parameters__") or not cls.__parameters__: - raise TypeError(f"{cls} is not a generic class") - elen = len(cls.__parameters__) alen = len(parameters) if alen != elen: expect_val = elen if hasattr(cls, "__parameters__"): parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] - num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) - if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): - return - # deal with TypeVarLike defaults - # required TypeVarLikes cannot appear after a defaulted one. - if alen < elen: - # since we validate TypeVarLike default in _collect_type_vars - # or _collect_parameters we can safely check parameters[alen] - if ( - getattr(parameters[alen], '__default__', NoDefault) - is not NoDefault - ): + if sys.version_info < (3, 11): + num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) + if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): return - num_default_tv = sum(getattr(p, '__default__', NoDefault) - is not NoDefault for p in parameters) - - elen -= num_default_tv - - expect_val = f"at least {elen}" - - raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" - f" for {cls}; actual {alen}, expected {expect_val}") -else: - # Python 3.11+ - - def _check_generic(cls, parameters, elen): - """Check correct count for parameters of a generic cls (internal helper). - - This gives a nice error message in case of count mismatch. - """ - if not elen: - raise TypeError(f"{cls} is not a generic class") - alen = len(parameters) - if alen != elen: - expect_val = elen - if hasattr(cls, "__parameters__"): - parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] - # deal with TypeVarLike defaults # required TypeVarLikes cannot appear after a defaulted one. if alen < elen: @@ -2807,7 +2704,6 @@ def _check_generic(cls, parameters, elen): raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" f" for {cls}; actual {alen}, expected {expect_val}") -if not _PEP_696_IMPLEMENTED: typing._check_generic = _check_generic @@ -3367,37 +3263,9 @@ def _raise_attribute_error(self, name: str) -> Never: def __repr__(self) -> str: return self.__name__ - if sys.version_info < (3, 11): - def _check_single_param(self, param, recursion=0): - # Allow [], [int], [int, str], [int, ...], [int, T] - if param is ...: - return ... - if param is None: - return None - if isinstance(param, list) and recursion == 0: - return [self._check_single_param(arg, recursion+1) - for arg in param] - return typing._type_check( - param, f'Subscripting {self.__name__} requires a type.' - ) - - def _check_parameters(self, parameters): - if sys.version_info < (3, 11): - return tuple( - self._check_single_param(item) - for item in parameters - ) - return tuple(typing._type_check( - item, f'Subscripting {self.__name__} requires a type.' - ) - for item in parameters - ) - def __getitem__(self, parameters): if not self.__type_params__: raise TypeError("Only generic type aliases are subscriptable") - if not isinstance(parameters, tuple): - parameters = (parameters,) return _types.GenericAlias(self, parameters) def __reduce__(self): @@ -3688,10 +3556,7 @@ def _eval_with_owner( if owner is None: owner = getattr(forward_ref, "__owner__", None) - if ( - globals is None - and getattr(forward_ref, "__forward_module__", None) is not None - ): + if globals is None and forward_ref.__forward_module__ is not None: globals = getattr( sys.modules.get(forward_ref.__forward_module__, None), "__dict__", None ) @@ -3806,7 +3671,7 @@ def evaluate_forward_ref( # Recursively evaluate the type if isinstance(value, ForwardRef): - if getattr(value, "__forward_module__", True) is not None: + if value.__forward_module__ is not None: globals = None return evaluate_forward_ref( value,