From 5139589bfcc7feaf618658005d0ae9cdbf4701db Mon Sep 17 00:00:00 2001 From: Khabib Shakhbanov <136262760+Khabib73@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:03:42 +0300 Subject: [PATCH 1/8] Update ruff target-version --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index bce4804b..4cb83987 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,7 @@ exclude = [] [tool.ruff] line-length = 90 -target-version = "py39" +target-version = "py310" [tool.ruff.lint] select = [ From 39afc13c263d6204d3a15c733454e7e301f928f1 Mon Sep 17 00:00:00 2001 From: Khabib <136262760+Khabib73@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:40:13 +0300 Subject: [PATCH 2/8] Remove 3.9 branches --- src/test_typing_extensions.py | 45 +++----- src/typing_extensions.py | 190 ++++++++-------------------------- 2 files changed, 58 insertions(+), 177 deletions(-) diff --git a/src/test_typing_extensions.py b/src/test_typing_extensions.py index 11f97ed8..84b14cb3 100644 --- a/src/test_typing_extensions.py +++ b/src/test_typing_extensions.py @@ -3958,20 +3958,17 @@ def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: ... with self.assertRaises(TypeError): MemoizedFunc[[int, str, str]] - if sys.version_info >= (3, 10): - # These unfortunately don't pass on 3.9, - # due to typing._type_check on older Python versions - X = MemoizedFunc[[int, str, str], T, T2] - self.assertEqual(X.__parameters__, (T, T2)) - self.assertEqual(X.__args__, ((int, str, str), T, T2)) + X = MemoizedFunc[[int, str, str], T, T2] + self.assertEqual(X.__parameters__, (T, T2)) + self.assertEqual(X.__args__, ((int, str, str), T, T2)) - Y = X[bytes, memoryview] - self.assertEqual(Y.__parameters__, ()) - self.assertEqual(Y.__args__, ((int, str, str), bytes, memoryview)) + Y = X[bytes, memoryview] + self.assertEqual(Y.__parameters__, ()) + self.assertEqual(Y.__args__, ((int, str, str), bytes, memoryview)) - # Regression test; fixing #126 might cause an error here - with self.assertRaisesRegex(TypeError, "not a generic class"): - Y[int] + # Regression test; fixing #126 might cause an error here + with self.assertRaisesRegex(TypeError, "not a generic class"): + Y[int] def test_protocol_generic_over_typevartuple(self): Ts = TypeVarTuple("Ts") @@ -6040,8 +6037,6 @@ class ProtoZ(Protocol[P]): G9[int] with self.subTest("Check list as parameter expression", klass=klass.__name__): - if sys.version_info < (3, 10): - self.skipTest("Cannot pass non-types") G5 = klass[[int, str, T]] self.assertEqual(G5.__parameters__, (T,)) self.assertEqual(G5.__args__, ((int, str, T),)) @@ -7182,8 +7177,6 @@ def test_typing_extensions_defers_when_possible(self): # as PEP 764 has not yet been accepted/implemented upstream. exclude = {'TypedDict', 'is_typeddict'} - if sys.version_info < (3, 10): - exclude |= {'get_args', 'get_origin'} if sys.version_info < (3, 10, 1): exclude |= {"Literal"} if sys.version_info < (3, 11): @@ -8402,18 +8395,14 @@ def test_cannot_delete_attributes(self): def test_or(self): Alias = TypeAliasType("Alias", int) - if sys.version_info >= (3, 10): - self.assertEqual(Alias | int, Union[Alias, int]) - self.assertEqual(Alias | None, Union[Alias, None]) - self.assertEqual(Alias | (int | str), Union[Alias, int | str]) - self.assertEqual(Alias | list[float], Union[Alias, list[float]]) - - if sys.version_info >= (3, 12): - Alias2 = typing.TypeAliasType("Alias2", str) - self.assertEqual(Alias | Alias2, Union[Alias, Alias2]) - else: - with self.assertRaises(TypeError): - Alias | int + self.assertEqual(Alias | int, Union[Alias, int]) + self.assertEqual(Alias | None, Union[Alias, None]) + self.assertEqual(Alias | (int | str), Union[Alias, int | str]) + self.assertEqual(Alias | list[float], Union[Alias, list[float]]) + + if sys.version_info >= (3, 12): + Alias2 = typing.TypeAliasType("Alias2", str) + self.assertEqual(Alias | Alias2, Union[Alias, Alias2]) # Rejected on all versions with self.assertRaises(TypeError): Alias | "Ref" diff --git a/src/typing_extensions.py b/src/typing_extensions.py index e84c053c..02b17656 100644 --- a/src/typing_extensions.py +++ b/src/typing_extensions.py @@ -256,13 +256,11 @@ def __repr__(self) -> str: def __call__(self, *args, **kwargs): raise TypeError(f"{type(self).__name__!r} object is not callable") - # Breakpoint: https://github.com/python/cpython/pull/21515 - if sys.version_info >= (3, 10): - def __or__(self, other): - return typing.Union[self, other] + def __or__(self, other): + return typing.Union[self, other] - def __ror__(self, other): - return typing.Union[other, self] + def __ror__(self, other): + return typing.Union[other, self] def __reduce__(self) -> str: """Reduce this sentinel to a singleton.""" @@ -276,15 +274,11 @@ def __reduce__(self) -> str: # The functions below are modified copies of typing internal helpers. # They are needed by _ProtocolMeta and they provide support for PEP 646. -# Breakpoint: https://github.com/python/cpython/pull/27342 -if sys.version_info >= (3, 10): - def _should_collect_from_parameters(t): - return isinstance( - t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) - ) -else: - def _should_collect_from_parameters(t): - return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) + +def _should_collect_from_parameters(t): + return isinstance( + t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) + ) NoReturn = typing.NoReturn @@ -1676,57 +1670,9 @@ def _clean_optional(obj, hints, globalns=None, localns=None): ): hints[name] = original_evaluated -# Python 3.9 has get_origin() and get_args() but those implementations don't support -# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. -# Breakpoint: https://github.com/python/cpython/pull/25298 -if sys.version_info >= (3, 10): - get_origin = typing.get_origin - get_args = typing.get_args -# 3.9 -else: - def get_origin(tp): - """Get the unsubscripted version of a type. - - This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar - and Annotated. Return None for unsupported types. Examples:: - - get_origin(Literal[42]) is Literal - get_origin(int) is None - get_origin(ClassVar[int]) is ClassVar - get_origin(Generic) is Generic - get_origin(Generic[T]) is Generic - get_origin(Union[T, int]) is Union - get_origin(List[Tuple[T, T]][int]) == list - get_origin(P.args) is P - """ - if isinstance(tp, typing._AnnotatedAlias): - return Annotated - if isinstance(tp, (typing._BaseGenericAlias, _types.GenericAlias, - ParamSpecArgs, ParamSpecKwargs)): - return tp.__origin__ - if tp is typing.Generic: - return typing.Generic - return None - - def get_args(tp): - """Get type arguments with all substitutions performed. - - For unions, basic simplifications used by Union constructor are performed. - Examples:: - get_args(Dict[str, int]) == (str, int) - get_args(int) == () - get_args(Union[int, Union[T, int], str][int]) == (int, str) - get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) - get_args(Callable[[], T][int]) == ([], int) - """ - if isinstance(tp, typing._AnnotatedAlias): - return (tp.__origin__, *tp.__metadata__) - if isinstance(tp, (typing._GenericAlias, _types.GenericAlias)): - res = tp.__args__ - if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: - res = (list(res[:-1]), res[-1]) - return res - return () + +get_origin = typing.get_origin +get_args = typing.get_args # 3.10+ @@ -2047,10 +1993,6 @@ def _type_convert(arg, module=None, *, allow_special_forms=False): if arg is None: return type(None) if isinstance(arg, str): - if sys.version_info <= (3, 9, 6): - return ForwardRef(arg) - if sys.version_info <= (3, 9, 7): - return ForwardRef(arg, module=module) return ForwardRef(arg, module=module, is_class=allow_special_forms) return arg else: @@ -2143,7 +2085,7 @@ def __getitem__(self, args): f" actual {alen}, expected {plen}" ) - subst = dict(zip(self.__parameters__, args)) + subst = dict(zip(self.__parameters__, args, strict=False)) # determine new args new_args = [] for arg in self.__args__: @@ -2222,9 +2164,6 @@ def _create_concatenate_alias(origin, parameters): # Remove dummy again concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ... for p in concatenate.__args__) - if sys.version_info < (3, 10): - # backport needs __args__ adjustment only - return concatenate concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__ if p is not _EllipsisDummy) return concatenate @@ -3156,24 +3095,18 @@ def wrapper(*args, **kwargs): f"a class or callable, not {arg!r}" ) -# Breakpoint: https://github.com/python/cpython/pull/23702 -if sys.version_info < (3, 10): - def _is_param_expr(arg): - return arg is ... or isinstance( - arg, (tuple, list, ParamSpec, _ConcatenateGenericAlias) - ) -else: - def _is_param_expr(arg): - return arg is ... or isinstance( - arg, - ( - tuple, - list, - ParamSpec, - _ConcatenateGenericAlias, - typing._ConcatenateGenericAlias, - ), - ) + +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 @@ -3705,16 +3638,11 @@ def __repr__(self): def __reduce__(self): return self.__qualname__ - # Breakpoint: https://github.com/python/cpython/pull/21515 - if sys.version_info >= (3, 10): - # PEP 604 methods - # It doesn't make sense to have these methods on Python <3.10 + def __or__(self, other): + return typing.Union[self, other] - def __or__(self, other): - return typing.Union[self, other] - - def __ror__(self, other): - return typing.Union[other, self] + def __ror__(self, other): + return typing.Union[other, self] # Breakpoint: https://github.com/python/cpython/pull/149172 @@ -3745,31 +3673,6 @@ def _is_unionable(obj): TypeAliasType, )) - if sys.version_info < (3, 10): - # Copied and pasted from https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Objects/genericaliasobject.c#L568-L582, - # so that we emulate the behaviour of `types.GenericAlias` - # on the latest versions of CPython - _ATTRIBUTE_DELEGATION_EXCLUSIONS = frozenset({ - "__class__", - "__bases__", - "__origin__", - "__args__", - "__unpacked__", - "__parameters__", - "__typing_unpacked_tuple_args__", - "__mro_entries__", - "__reduce_ex__", - "__reduce__", - "__copy__", - "__deepcopy__", - }) - - class _TypeAliasGenericAlias(typing._GenericAlias, _root=True): - def __getattr__(self, attr): - if attr in _ATTRIBUTE_DELEGATION_EXCLUSIONS: - return object.__getattr__(self, attr) - return getattr(self.__origin__, attr) - class TypeAliasType: """Create named, parameterized type aliases. @@ -3894,16 +3797,7 @@ def __getitem__(self, parameters): if not isinstance(parameters, tuple): parameters = (parameters,) # Using 3.9 here will create problems with Concatenate - if sys.version_info >= (3, 10): - return _types.GenericAlias(self, parameters) - type_vars = _collect_type_vars(parameters) - parameters = self._check_parameters(parameters) - alias = _TypeAliasGenericAlias(self, parameters) - # alias.__parameters__ is not complete if Concatenate is present - # as it is converted to a list from which no parameters are extracted. - if alias.__parameters__ != type_vars: - alias.__parameters__ = type_vars - return alias + return _types.GenericAlias(self, parameters) def __reduce__(self): return self.__name__ @@ -3918,19 +3812,17 @@ def __init_subclass__(cls, *args, **kwargs): def __call__(self): raise TypeError("Type alias is not callable") - # Breakpoint: https://github.com/python/cpython/pull/21515 - if sys.version_info >= (3, 10): - def __or__(self, right): - # For forward compatibility with 3.12, reject Unions - # that are not accepted by the built-in Union. - if not _is_unionable(right): - return NotImplemented - return typing.Union[self, right] - - def __ror__(self, left): - if not _is_unionable(left): - return NotImplemented - return typing.Union[left, self] + def __or__(self, right): + # For forward compatibility with 3.12, reject Unions + # that are not accepted by the built-in Union. + if not _is_unionable(right): + return NotImplemented + return typing.Union[self, right] + + def __ror__(self, left): + if not _is_unionable(left): + return NotImplemented + return typing.Union[left, self] if hasattr(typing, "is_protocol"): From afa22269d7b30500556cda946681d216dd7a5f02 Mon Sep 17 00:00:00 2001 From: Khabib <136262760+Khabib73@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:34:44 +0300 Subject: [PATCH 3/8] Small improvements --- pyproject.toml | 1 - src/typing_extensions.py | 18 +++++------------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4cb83987..9c167e04 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,6 @@ exclude = [] [tool.ruff] line-length = 90 -target-version = "py310" [tool.ruff.lint] select = [ diff --git a/src/typing_extensions.py b/src/typing_extensions.py index 02b17656..14d9d1bf 100644 --- a/src/typing_extensions.py +++ b/src/typing_extensions.py @@ -271,16 +271,6 @@ def __reduce__(self) -> str: _marker = sentinel("sentinel") -# The functions below are modified copies of typing internal helpers. -# They are needed by _ProtocolMeta and they provide support for PEP 646. - - -def _should_collect_from_parameters(t): - return isinstance( - t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) - ) - - NoReturn = typing.NoReturn # Some unconstrained type variables. These are used by the container types. @@ -2084,7 +2074,8 @@ def __getitem__(self, args): f"Too {'many' if alen > plen else 'few'} arguments for {self};" f" actual {alen}, expected {plen}" ) - + # Explicit strict=False for backwards compatibility + # and to match CPython's equivalent implementation. subst = dict(zip(self.__parameters__, args, strict=False)) # determine new args new_args = [] @@ -3283,7 +3274,9 @@ def _collect_type_vars(types, typevar_types=None): ' follows type parameter with a default') tvars.append(t) - if _should_collect_from_parameters(t): + if isinstance(t, (typing._GenericAlias, + _types.GenericAlias, + _types.UnionType)): tvars.extend([t for t in t.__parameters__ if t not in tvars]) elif isinstance(t, tuple): # Collect nested type_vars @@ -3796,7 +3789,6 @@ def __getitem__(self, parameters): raise TypeError("Only generic type aliases are subscriptable") if not isinstance(parameters, tuple): parameters = (parameters,) - # Using 3.9 here will create problems with Concatenate return _types.GenericAlias(self, parameters) def __reduce__(self): From 5bb3c50e7cca14c1ccb332e23f15163f0be07581 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Thu, 26 Nov 2026 23:46:36 +0000 Subject: [PATCH 4/8] Nits --- src/typing_extensions.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/typing_extensions.py b/src/typing_extensions.py index 14d9d1bf..cb4ed4e9 100644 --- a/src/typing_extensions.py +++ b/src/typing_extensions.py @@ -3157,9 +3157,7 @@ def _check_generic(cls, parameters, elen=_marker): expect_val = f"at least {elen}" - # Breakpoint: https://github.com/python/cpython/pull/27515 - things = "arguments" if sys.version_info >= (3, 10) else "parameters" - raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}" + raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" f" for {cls}; actual {alen}, expected {expect_val}") else: # Python 3.11+ @@ -3274,9 +3272,10 @@ def _collect_type_vars(types, typevar_types=None): ' follows type parameter with a default') tvars.append(t) - if isinstance(t, (typing._GenericAlias, - _types.GenericAlias, - _types.UnionType)): + if isinstance( + t, + (typing._GenericAlias, _types.GenericAlias, _types.UnionType) + ): tvars.extend([t for t in t.__parameters__ if t not in tvars]) elif isinstance(t, tuple): # Collect nested type_vars From fdcf7cabb829cbcb99a3862bb8f39deda0419300 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Fri, 27 Nov 2026 00:14:17 +0000 Subject: [PATCH 5/8] More --- src/test_typing_extensions.py | 112 ++++++++-------------------------- 1 file changed, 26 insertions(+), 86 deletions(-) diff --git a/src/test_typing_extensions.py b/src/test_typing_extensions.py index 84b14cb3..a283d62e 100644 --- a/src/test_typing_extensions.py +++ b/src/test_typing_extensions.py @@ -112,10 +112,6 @@ KT = TypeVar("KT") VT = TypeVar("VT") -# Flags used to mark tests that only apply after a specific -# version of the typing module. -TYPING_3_10_0 = sys.version_info[:3] >= (3, 10, 0) - # 3.11 makes runtime type checks (_type_check) more lenient. TYPING_3_11_0 = sys.version_info[:3] >= (3, 11, 0) @@ -553,7 +549,6 @@ def test_pickle(self): pickled = pickle.dumps(self.bottom_type, protocol=proto) self.assertIs(self.bottom_type, pickle.loads(pickled)) - @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be") def test_or(self): self.assertEqual(self.bottom_type | int, Union[self.bottom_type, int]) self.assertEqual(int | self.bottom_type, Union[int, self.bottom_type]) @@ -1372,7 +1367,6 @@ class Ints(enum.IntEnum): self.assertEqual(Union[Literal[1], Literal[Ints.B], Literal[True]].__args__, (Literal[1], Literal[Ints.B], Literal[True])) - @skipUnless(TYPING_3_10_0, "Python 3.10+ required") def test_or_type_operator_with_Literal(self): self.assertEqual((Literal[1] | Literal[2]).__args__, (Literal[1], Literal[2])) @@ -1799,6 +1793,8 @@ def test_annotation_and_optional_default(self): Union[str, "Union[None, StrAlias]"]: Optional[str], Union["annotation", T_default] : Union[annotation, T_default], Annotated["annotation", "nested"] : Annotated[Union[int, None], "data", "nested"], + "str | NoneAlias | StrAlias" : str | None, + str | None : Optional[str], # Note: A starred *Ts will use typing.Unpack in 3.11+ see Issue #485 Unpack[Ts] : Unpack[Ts], } @@ -1808,9 +1804,6 @@ def test_annotation_and_optional_default(self): do_not_stringify_cases[Unpack[Ts]] = Unpack[Ts] else: cases[Unpack[Ts]] = Unpack[Ts] - if TYPING_3_10_0: # cannot construct UnionTypes before 3.10 - do_not_stringify_cases["str | NoneAlias | StrAlias"] = str | None - cases[str | None] = Optional[str] cases.update(do_not_stringify_cases) for (annot, expected), none_default, as_str, wrap_optional in itertools.product( cases.items(), (False, True), (False, True), (False, True) @@ -2257,7 +2250,6 @@ class B: ... A.register(B) self.assertIsSubclass(B, typing_extensions.Generator) - @skipIf(sys.version_info < (3, 10), "PEP 604 has yet to be") def test_or_and_ror(self): self.assertEqual( typing_extensions.Generator | typing_extensions.AsyncGenerator, @@ -2410,7 +2402,6 @@ def test_errors(self): class D(UserId): pass - @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be") def test_or(self): for cls in (int, self.UserName): with self.subTest(cls=cls): @@ -3644,11 +3635,6 @@ class P(PR[int, T], Protocol[T]): PR[int] with self.assertRaises(TypeError): P[int, str] - if not TYPING_3_10_0: - with self.assertRaises(TypeError): - PR[int, 1] - with self.assertRaises(TypeError): - PR[int, ClassVar] class C(PR[int, T]): pass self.assertIsInstance(C[str](), C) @@ -3665,9 +3651,6 @@ class P(PR[int, str], Protocol): self.assertIsSubclass(P, PR) with self.assertRaises(TypeError): PR[int] - if not TYPING_3_10_0: - with self.assertRaises(TypeError): - PR[int, 1] class P1(Protocol, Generic[T]): def bar(self, x: T) -> str: ... class P2(Generic[T], Protocol): @@ -3680,9 +3663,6 @@ class Test: def bar(self, x: str) -> str: return x # pragma: no cover self.assertIsInstance(Test(), PSub) - if not TYPING_3_10_0: - with self.assertRaises(TypeError): - PR[int, ClassVar] if hasattr(typing, "TypeAliasType"): exec(textwrap.dedent( @@ -3982,14 +3962,12 @@ def __call__(self, *args: Unpack[Ts]) -> T: ... self.assertEqual(MemoizedFunc.__parameters__, (Ts, T, T2)) self.assertTrue(MemoizedFunc._is_protocol) - things = "arguments" if sys.version_info >= (3, 10) else "parameters" - # A bug was fixed in 3.11.1 # (https://github.com/python/cpython/commit/74920aa27d0c57443dd7f704d6272cca9c507ab3) # That means this assertion doesn't pass on 3.11.0, # but it passes on all other Python versions if sys.version_info[:3] != (3, 11, 0): - with self.assertRaisesRegex(TypeError, f"Too few {things}"): + with self.assertRaisesRegex(TypeError, f"Too few arguments"): MemoizedFunc[int] X = MemoizedFunc[int, T, T2] @@ -5446,7 +5424,6 @@ class A(TypedDict): def test_dunder_dict(self): self.assertIsInstance(TypedDict.__dict__, dict) - @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be") def test_or(self): class TD(TypedDict): a: int @@ -5922,7 +5899,6 @@ class X(Generic[T, P]): class Y(Protocol[T, P]): pass - things = "arguments" if sys.version_info >= (3, 10) else "parameters" for klass in X, Y: with self.subTest(klass=klass.__name__): G1 = klass[int, P_2] @@ -5939,7 +5915,7 @@ class Y(Protocol[T, P]): with self.assertRaisesRegex( TypeError, - f"Too few {things} for {klass}" + f"Too few arguments for {klass}" ): klass[int] @@ -5962,16 +5938,13 @@ class ProtoZ(Protocol[P]): for klass in Z, ProtoZ: with self.subTest(klass=klass.__name__): - # Note: For 3.10+ __args__ are nested tuples here ((int, ),) instead of (int, ) G6 = klass[int, str, T] - G6args = G6.__args__[0] if sys.version_info >= (3, 10) else G6.__args__ - self.assertEqual(G6args, (int, str, T)) + self.assertEqual(G6.__args__[0], (int, str, T)) self.assertEqual(G6.__parameters__, (T,)) # P = [int] G7 = klass[int] - G7args = G7.__args__[0] if sys.version_info >= (3, 10) else G7.__args__ - self.assertEqual(G7args, (int,)) + self.assertEqual(G7.__args__[0], (int,)) self.assertEqual(G7.__parameters__, ()) G8 = klass[Concatenate[T, ...]] @@ -5983,10 +5956,8 @@ class ProtoZ(Protocol[P]): # This is an invalid form but useful for testing correct substitution G10 = klass[int, Concatenate[str, P]] - G10args = G10.__args__[0] if sys.version_info >= (3, 10) else G10.__args__ - self.assertEqual(G10args, (int, Concatenate[str, P], )) + self.assertEqual(G10.__args__[0], (int, Concatenate[str, P], )) - @skipUnless(TYPING_3_10_0, "ParamSpec not present before 3.10") def test_is_param_expr(self): P = ParamSpec("P") P_typing = typing.ParamSpec("P_typing") @@ -6007,7 +5978,6 @@ class Z(Generic[P]): class ProtoZ(Protocol[P]): pass - things = "arguments" if sys.version_info >= (3, 10) else "parameters" for klass in Z, ProtoZ: with self.subTest(klass=klass.__name__): G8 = klass[Concatenate[T, ...]] @@ -6025,15 +5995,14 @@ class ProtoZ(Protocol[P]): G9 = klass[Concatenate[T, P_2]] self.assertEqual(G9.__parameters__, (T, P_2)) - with self.assertRaisesRegex(TypeError, - "The last parameter to Concatenate should be a ParamSpec variable or ellipsis." - if sys.version_info < (3, 10) else + with self.assertRaisesRegex( + TypeError, # from __typing_subst__ "Expected a list of types, an ellipsis, ParamSpec, or Concatenate" ): G9[int, int] - with self.assertRaisesRegex(TypeError, f"Too few {things}"): + with self.assertRaisesRegex(TypeError, f"Too few arguments"): G9[int] with self.subTest("Check list as parameter expression", klass=klass.__name__): @@ -6052,10 +6021,8 @@ class ProtoZ(Protocol[P]): if (3, 10) <= sys.version_info < (3, 11, 3): self.skipTest("3.10-3.11.2 does not substitute Concatenate here") self.assertEqual(H10.__parameters__, ()) - H10args = H10.__args__[0] if sys.version_info >= (3, 10) else H10.__args__ - self.assertEqual(H10args, (int, (str, int))) + self.assertEqual(H10.__args__[0], (int, (str, int))) - @skipUnless(TYPING_3_10_0, "ParamSpec not present before 3.10") def test_substitution_with_typing_variants(self): # verifies substitution and typing._check_generic working with typing variants P = ParamSpec("P") @@ -6164,7 +6131,6 @@ class MyClass: ... self.assertNotEqual(d, c) self.assertNotEqual(d, Concatenate) - @skipUnless(TYPING_3_10_0, "Concatenate not available in <3.10") def test_typing_compatibility(self): P = ParamSpec('P') C1 = Concatenate[int, P][typing.Concatenate[int, P]] @@ -6229,7 +6195,6 @@ def test_invalid_uses(self): ): Concatenate[(str,), P] - @skipUnless(TYPING_3_10_0, "Missing backport to 3.9. See issue #48") def test_alias_subscription_with_ellipsis(self): P = ParamSpec('P') X = Callable[Concatenate[int, P], Any] @@ -6296,7 +6261,6 @@ def test_substitution(self): C3 = Concatenate[str, T, P] self.assertEqual(C3[int, [bool]], (str, int, bool)) - @skipUnless(TYPING_3_10_0, "Concatenate not present before 3.10") def test_is_param_expr(self): P = ParamSpec('P') concat = Concatenate[str, P] @@ -6552,7 +6516,6 @@ def test_pickle(self): pickled = pickle.dumps(LiteralString, protocol=proto) self.assertIs(LiteralString, pickle.loads(pickled)) - @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be") def test_or(self): self.assertEqual(LiteralString | int, Union[LiteralString, int]) self.assertEqual(int | LiteralString, Union[int, LiteralString]) @@ -6607,7 +6570,6 @@ def test_pickle(self): pickled = pickle.dumps(Self, protocol=proto) self.assertIs(Self, pickle.loads(pickled)) - @skipUnless(TYPING_3_10_0, "PEP 604 has yet to be") def test_or(self): self.assertEqual(Self | int, Union[Self, int]) self.assertEqual(int | Self, Union[int, Self]) @@ -7375,8 +7337,7 @@ class Y(Generic[T], NamedTuple): self.assertIsInstance(a, G) self.assertEqual(a.x, 3) - things = "arguments" if sys.version_info >= (3, 10) else "parameters" - with self.assertRaisesRegex(TypeError, f'Too many {things}'): + with self.assertRaisesRegex(TypeError, f'Too many arguments'): G[int, str] def test_non_generic_subscript_py39_plus(self): @@ -7733,16 +7694,15 @@ def test_union_unique(self): self.assertEqual(Union[X, int].__parameters__, (X,)) self.assertIs(Union[X, int].__origin__, Union) - if hasattr(types, "UnionType"): - def test_or(self): - X = TypeVar('X') - # use a string because str doesn't implement - # __or__/__ror__ itself - self.assertEqual(X | "x", Union[X, "x"]) - self.assertEqual("x" | X, Union["x", X]) - # make sure the order is correct - self.assertEqual(get_args(X | "x"), (X, EqualToForwardRef("x"))) - self.assertEqual(get_args("x" | X), (EqualToForwardRef("x"), X)) + def test_or(self): + X = TypeVar('X') + # use a string because str doesn't implement + # __or__/__ror__ itself + self.assertEqual(X | "x", Union[X, "x"]) + self.assertEqual("x" | X, Union["x", X]) + # make sure the order is correct + self.assertEqual(get_args(X | "x"), (X, EqualToForwardRef("x"))) + self.assertEqual(get_args("x" | X), (EqualToForwardRef("x"), X)) def test_union_constrained(self): A = TypeVar('A', str, bytes) @@ -7826,11 +7786,10 @@ def test_paramspec(self): self.assertEqual(P.__default__, [str, int]) self.assertTrue(P.has_default()) self.assertIsInstance(P, ParamSpec) - if hasattr(typing, "ParamSpec"): - self.assertIsInstance(P, typing.ParamSpec) - typing_P = typing.ParamSpec('P') - self.assertIsInstance(typing_P, typing.ParamSpec) - self.assertIsInstance(typing_P, ParamSpec) + self.assertIsInstance(P, typing.ParamSpec) + typing_P = typing.ParamSpec('P') + self.assertIsInstance(typing_P, typing.ParamSpec) + self.assertIsInstance(typing_P, ParamSpec) class A(Generic[P]): ... self.assertEqual(typing.Callable[P, None].__args__, (P, type(None))) @@ -8472,13 +8431,8 @@ def test_callable_with_concatenate(self): self.assertEqual(callable_concat.__parameters__, (P2,)) concat_usage = callable_concat[str] with self.subTest("get_args of Concatenate in TypeAliasType"): - if not TYPING_3_10_0: - # args are: ([, ~P2],) - self.skipTest("Nested ParamSpec is not substituted") self.assertEqual(get_args(concat_usage), ((int, str),)) with self.subTest("Equality of parameter_expression without []"): - if not TYPING_3_10_0: - self.skipTest("Nested list is invalid type form") self.assertEqual(concat_usage, callable_concat[[str]]) def test_substitution(self): @@ -8525,16 +8479,6 @@ def test_wrong_amount_of_parameters(self): self.assertEqual(get_args(alias), expected_args) self.assertEqual(alias.__parameters__, expected_params) - # The condition should align with the version of GeneriAlias usage in __getitem__ or be 3.11+ - @skipIf(TYPING_3_10_0, "Most arguments are allowed in 3.11+ or with GenericAlias") - def test_invalid_cases_before_3_10(self): - T = TypeVar('T') - ListOrSetT = TypeAliasType("ListOrSetT", Union[List[T], Set[T]], type_params=(T,)) - with self.assertRaises(TypeError): - ListOrSetT[Generic[T]] - with self.assertRaises(TypeError): - ListOrSetT[(Generic[T], )] - def test_unpack_parameter_collection(self): Ts = TypeVarTuple("Ts") @@ -8619,7 +8563,6 @@ def test_type_var_compatibility(self): T4 = TypeAliasType("TypingExtTypeVarTuple", ..., type_params=(textTs,)) self.assertEqual(T4.__type_params__, (textTs,)) - @skipUnless(TYPING_3_10_0, "typing.ParamSpec is not available before 3.10") def test_param_spec_compatibility(self): # Regression test to assure compatibility with typing variant typingP = typing.ParamSpec("typingP") @@ -9412,7 +9355,6 @@ def test_evaluate_forward_ref_nested(self): why = typing_extensions.ForwardRef('"\'str\'"') self.assertIs(typing_extensions.evaluate_forward_ref(why), str) - @skipUnless(sys.version_info >= (3, 10), "Relies on PEP 604") def test_evaluate_forward_ref_nested_pep604(self): ref = typing_extensions.ForwardRef("int | list['str']") if sys.version_info >= (3, 11): @@ -9486,8 +9428,7 @@ def test_partial_evaluation(self): ) def test_global_constant(self): - if sys.version_info[:3] > (3, 10, 0): - self.assertTrue(_FORWARD_REF_HAS_CLASS) + self.assertTrue(_FORWARD_REF_HAS_CLASS) def test_forward_ref_fallback(self): with self.assertRaises(NameError): @@ -9681,7 +9622,6 @@ def test_sentinel_keyword_repr(self): self.assertEqual(repr(sentinel_keyword_repr), 'keyword_repr') - @skipIf(sys.version_info < (3, 10), reason='New unions not available in 3.9') def test_sentinel_type_expression_union(self): sentinel_type = sentinel('sentinel') From 0b15164b4c20081345223c205d0ba36d73884965 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Fri, 27 Nov 2026 00:19:56 +0000 Subject: [PATCH 6/8] Fix formatting of TypeError messages in tests --- src/test_typing_extensions.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test_typing_extensions.py b/src/test_typing_extensions.py index a283d62e..08849add 100644 --- a/src/test_typing_extensions.py +++ b/src/test_typing_extensions.py @@ -3967,7 +3967,7 @@ def __call__(self, *args: Unpack[Ts]) -> T: ... # That means this assertion doesn't pass on 3.11.0, # but it passes on all other Python versions if sys.version_info[:3] != (3, 11, 0): - with self.assertRaisesRegex(TypeError, f"Too few arguments"): + with self.assertRaisesRegex(TypeError, "Too few arguments"): MemoizedFunc[int] X = MemoizedFunc[int, T, T2] @@ -6002,7 +6002,7 @@ class ProtoZ(Protocol[P]): ): G9[int, int] - with self.assertRaisesRegex(TypeError, f"Too few arguments"): + with self.assertRaisesRegex(TypeError, "Too few arguments"): G9[int] with self.subTest("Check list as parameter expression", klass=klass.__name__): @@ -7337,7 +7337,7 @@ class Y(Generic[T], NamedTuple): self.assertIsInstance(a, G) self.assertEqual(a.x, 3) - with self.assertRaisesRegex(TypeError, f'Too many arguments'): + with self.assertRaisesRegex(TypeError, 'Too many arguments'): G[int, str] def test_non_generic_subscript_py39_plus(self): From e726c5802570ce63e52ff0328c2974d63f018b6d Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Fri, 27 Nov 2026 00:34:45 +0000 Subject: [PATCH 7/8] More --- src/typing_extensions.py | 454 +++------------------------------------ 1 file changed, 29 insertions(+), 425 deletions(-) diff --git a/src/typing_extensions.py b/src/typing_extensions.py index cb4ed4e9..462faf3e 100644 --- a/src/typing_extensions.py +++ b/src/typing_extensions.py @@ -1134,9 +1134,6 @@ def __reduce__(self): _TypedDictMeta = typing._TypedDictMeta is_typeddict = typing.is_typeddict else: - # 3.10.0 and later - _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters - def _get_typeddict_qualifiers(annotation_type): while True: annotation_origin = get_origin(annotation_type) @@ -1212,16 +1209,10 @@ def __new__(cls, name, bases, ns, *, total=True, closed=None, else: own_annotations = {} msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" - if _TAKES_MODULE: - own_checked_annotations = { - n: typing._type_check(tp, msg, module=tp_dict.__module__) - for n, tp in own_annotations.items() - } - else: - own_checked_annotations = { - n: typing._type_check(tp, msg) - for n, tp in own_annotations.items() - } + own_checked_annotations = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own_annotations.items() + } required_keys = set() optional_keys = set() readonly_keys = set() @@ -1541,12 +1532,12 @@ def _strip_extras(t): if stripped_args == t.__args__: return t return t.copy_with(stripped_args) - if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): + if isinstance(t, _types.GenericAlias): stripped_args = tuple(_strip_extras(a) for a in t.__args__) if stripped_args == t.__args__: return t return _types.GenericAlias(t.__origin__, stripped_args) - if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): + if isinstance(t, _types.UnionType): stripped_args = tuple(_strip_extras(a) for a in t.__args__) if stripped_args == t.__args__: return t @@ -1654,8 +1645,7 @@ def _clean_optional(obj, hints, globalns=None, localns=None): # value might be cached by typing._tp_cache contrary to original_evaluated if original_evaluated != value or ( # 3.10: ForwardRefs of UnionType might be turned into _UnionGenericAlias - hasattr(_types, "UnionType") - and isinstance(original_evaluated, _types.UnionType) + isinstance(original_evaluated, _types.UnionType) and not isinstance(value, _types.UnionType) ): hints[name] = original_evaluated @@ -1663,27 +1653,7 @@ def _clean_optional(obj, hints, globalns=None, localns=None): get_origin = typing.get_origin get_args = typing.get_args - - -# 3.10+ -if hasattr(typing, 'TypeAlias'): - TypeAlias = typing.TypeAlias -# 3.9 -else: - @_ExtensionsSpecialForm - def TypeAlias(self, parameters): - """Special marker indicating that an assignment should - be recognized as a proper type alias definition by type - checkers. - - For example:: - - Predicate: TypeAlias = Callable[..., bool] - - It's invalid when used anywhere except as in the example above. - """ - raise TypeError(f"{self} is not subscriptable") - +TypeAlias = typing.TypeAlias def _set_default(type_param, default): type_param.has_default = lambda: default is not NoDefault @@ -1752,74 +1722,15 @@ def __init_subclass__(cls) -> None: raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") -# Python 3.10+ has PEP 612 -if hasattr(typing, 'ParamSpecArgs'): - ParamSpecArgs = typing.ParamSpecArgs - ParamSpecKwargs = typing.ParamSpecKwargs -# 3.9 -else: - class _Immutable: - """Mixin to indicate that object should not be copied.""" - __slots__ = () - - def __copy__(self): - return self - - def __deepcopy__(self, memo): - return self - - class ParamSpecArgs(_Immutable): - """The args for a ParamSpec object. - - Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. - - ParamSpecArgs objects have a reference back to their ParamSpec: - - P.args.__origin__ is P - - This type is meant for runtime introspection and has no special meaning to - static type checkers. - """ - def __init__(self, origin): - self.__origin__ = origin - - def __repr__(self): - return f"{self.__origin__.__name__}.args" - - def __eq__(self, other): - if not isinstance(other, ParamSpecArgs): - return NotImplemented - return self.__origin__ == other.__origin__ - - class ParamSpecKwargs(_Immutable): - """The kwargs for a ParamSpec object. - - Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. - - ParamSpecKwargs objects have a reference back to their ParamSpec: - - P.kwargs.__origin__ is P - - This type is meant for runtime introspection and has no special meaning to - static type checkers. - """ - def __init__(self, origin): - self.__origin__ = origin - - def __repr__(self): - return f"{self.__origin__.__name__}.kwargs" - - def __eq__(self, other): - if not isinstance(other, ParamSpecKwargs): - return NotImplemented - return self.__origin__ == other.__origin__ +ParamSpecArgs = typing.ParamSpecArgs +ParamSpecKwargs = typing.ParamSpecKwargs if _PEP_696_IMPLEMENTED: from typing import ParamSpec # 3.10+ -elif hasattr(typing, 'ParamSpec'): +else: # Add default parameter - PEP 696 class ParamSpec(metaclass=_TypeVarLikeMeta): @@ -1867,297 +1778,41 @@ def _paramspec_prepare_subst(alias, args): def __init_subclass__(cls) -> None: raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") -# 3.9 -else: - - # Inherits from list as a workaround for Callable checks in Python < 3.9.2. - class ParamSpec(list, _DefaultMixin): - """Parameter specification variable. - - Usage:: - - P = ParamSpec('P') - - Parameter specification variables exist primarily for the benefit of static - type checkers. They are used to forward the parameter types of one - callable to another callable, a pattern commonly found in higher order - functions and decorators. They are only valid when used in ``Concatenate``, - or s the first argument to ``Callable``. In Python 3.10 and higher, - they are also supported in user-defined Generics at runtime. - See class Generic for more information on generic types. An - example for annotating a decorator:: - - T = TypeVar('T') - P = ParamSpec('P') - - def add_logging(f: Callable[P, T]) -> Callable[P, T]: - '''A type-safe decorator to add logging to a function.''' - def inner(*args: P.args, **kwargs: P.kwargs) -> T: - logging.info(f'{f.__name__} was called') - return f(*args, **kwargs) - return inner - - @add_logging - def add_two(x: float, y: float) -> float: - '''Add two numbers together.''' - return x + y - - Parameter specification variables defined with covariant=True or - contravariant=True can be used to declare covariant or contravariant - generic types. These keyword arguments are valid, but their actual semantics - are yet to be decided. See PEP 612 for details. - - Parameter specification variables can be introspected. e.g.: - - P.__name__ == 'T' - P.__bound__ == None - P.__covariant__ == False - P.__contravariant__ == False - - Note that only parameter specification variables defined in global scope can - be pickled. - """ - - # Trick Generic __parameters__. - __class__ = typing.TypeVar - - @property - def args(self): - return ParamSpecArgs(self) - - @property - def kwargs(self): - return ParamSpecKwargs(self) - - def __init__(self, name, *, bound=None, covariant=False, contravariant=False, - infer_variance=False, default=NoDefault): - list.__init__(self, [self]) - self.__name__ = name - self.__covariant__ = bool(covariant) - self.__contravariant__ = bool(contravariant) - self.__infer_variance__ = bool(infer_variance) - self.__bound__ = bound - _DefaultMixin.__init__(self, default) - - # for pickling: - def_mod = _caller() - if def_mod != 'typing_extensions': - self.__module__ = def_mod - - def __repr__(self): - if self.__infer_variance__: - prefix = '' - elif self.__covariant__: - prefix = '+' - elif self.__contravariant__: - prefix = '-' - else: - prefix = '~' - return prefix + self.__name__ - - def __hash__(self): - return object.__hash__(self) - - def __eq__(self, other): - return self is other - - def __reduce__(self): - return self.__name__ - - # Hack to get typing._type_check to pass. - def __call__(self, *args, **kwargs): - pass - - def __init_subclass__(cls) -> None: - raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") - - -# 3.9 -if not hasattr(typing, 'Concatenate'): - # Inherits from list as a workaround for Callable checks in Python < 3.9.2. - - # 3.9.0-1 - if not hasattr(typing, '_type_convert'): - def _type_convert(arg, module=None, *, allow_special_forms=False): - """For converting None to type(None), and strings to ForwardRef.""" - if arg is None: - return type(None) - if isinstance(arg, str): - return ForwardRef(arg, module=module, is_class=allow_special_forms) - return arg - else: - _type_convert = typing._type_convert - - class _ConcatenateGenericAlias(list): - - # Trick Generic into looking into this for __parameters__. - __class__ = typing._GenericAlias - - def __init__(self, origin, args): - # Cannot use `super().__init__` here because of the `__class__` assignment - # in the class body (https://github.com/python/typing_extensions/issues/661) - list.__init__(self, args) - self.__origin__ = origin - self.__args__ = args - - def __repr__(self): - _type_repr = typing._type_repr - return (f'{_type_repr(self.__origin__)}' - f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') - def __hash__(self): - return hash((self.__origin__, self.__args__)) +_ConcatenateGenericAlias = typing._ConcatenateGenericAlias - # Hack to get typing._type_check to pass in Generic. - def __call__(self, *args, **kwargs): - pass +# 3.10 +if sys.version_info < (3, 11): - @property - def __parameters__(self): - return tuple( - tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) - ) + class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True): + # needed for checks in collections.abc.Callable to accept this class + __module__ = "typing" - # 3.9 used by __getitem__ below def copy_with(self, params): - if isinstance(params[-1], _ConcatenateGenericAlias): - params = (*params[:-1], *params[-1].__args__) - elif isinstance(params[-1], (list, tuple)): + if isinstance(params[-1], (list, tuple)): return (*params[:-1], *params[-1]) - elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))): + if isinstance(params[-1], typing._ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)): raise TypeError("The last parameter to Concatenate should be a " "ParamSpec variable or ellipsis.") - return self.__class__(self.__origin__, params) + return super(typing._ConcatenateGenericAlias, self).copy_with(params) - # 3.9; accessed during GenericAlias.__getitem__ when substituting def __getitem__(self, args): - if self.__origin__ in (Generic, Protocol): - # Can't subscript Generic[...] or Protocol[...]. - raise TypeError(f"Cannot subscript already-subscripted {self}") - if not self.__parameters__: - raise TypeError(f"{self} is not a generic class") - - if not isinstance(args, tuple): - args = (args,) - args = _unpack_args(*(_type_convert(p) for p in args)) - params = self.__parameters__ - for param in params: - prepare = getattr(param, "__typing_prepare_subst__", None) - if prepare is not None: - args = prepare(self, args) - # 3.9 & typing.ParamSpec - elif isinstance(param, ParamSpec): - i = params.index(param) - if ( - i == len(args) - and getattr(param, '__default__', NoDefault) is not NoDefault - ): - args = [*args, param.__default__] - if i >= len(args): - raise TypeError(f"Too few arguments for {self}") - # Special case for Z[[int, str, bool]] == Z[int, str, bool] - if len(params) == 1 and not _is_param_expr(args[0]): - assert i == 0 - args = (args,) - elif ( - isinstance(args[i], list) - # 3.9 - # This class inherits from list do not convert - and not isinstance(args[i], _ConcatenateGenericAlias) - ): - args = (*args[:i], tuple(args[i]), *args[i + 1:]) - - alen = len(args) - plen = len(params) - if alen != plen: - raise TypeError( - f"Too {'many' if alen > plen else 'few'} arguments for {self};" - f" actual {alen}, expected {plen}" - ) - # Explicit strict=False for backwards compatibility - # and to match CPython's equivalent implementation. - subst = dict(zip(self.__parameters__, args, strict=False)) - # determine new args - new_args = [] - for arg in self.__args__: - if isinstance(arg, type): - new_args.append(arg) - continue - if isinstance(arg, TypeVar): - arg = subst[arg] - if ( - (isinstance(arg, typing._GenericAlias) and _is_unpack(arg)) - or ( - hasattr(_types, "GenericAlias") - and isinstance(arg, _types.GenericAlias) - and getattr(arg, "__unpacked__", False) - ) - ): - raise TypeError(f"{arg} is not valid as type argument") - - elif isinstance(arg, - typing._GenericAlias - if not hasattr(_types, "GenericAlias") else - (typing._GenericAlias, _types.GenericAlias) - ): - subparams = arg.__parameters__ - if subparams: - subargs = tuple(subst[x] for x in subparams) - arg = arg[subargs] - new_args.append(arg) - return self.copy_with(tuple(new_args)) - -# 3.10+ -else: - _ConcatenateGenericAlias = typing._ConcatenateGenericAlias - - # 3.10 - if sys.version_info < (3, 11): - - class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True): - # needed for checks in collections.abc.Callable to accept this class - __module__ = "typing" - - def copy_with(self, params): - if isinstance(params[-1], (list, tuple)): - return (*params[:-1], *params[-1]) - if isinstance(params[-1], typing._ConcatenateGenericAlias): - params = (*params[:-1], *params[-1].__args__) - elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)): - raise TypeError("The last parameter to Concatenate should be a " - "ParamSpec variable or ellipsis.") - return super(typing._ConcatenateGenericAlias, self).copy_with(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 value - - -# 3.9.2 -class _EllipsisDummy: ... + 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 value # <=3.10 def _create_concatenate_alias(origin, parameters): - if parameters[-1] is ... and sys.version_info < (3, 9, 2): - # Hack: Arguments must be types, replace it with one. - parameters = (*parameters[:-1], _EllipsisDummy) if sys.version_info >= (3, 10, 3): - concatenate = _ConcatenateGenericAlias(origin, parameters, + return _ConcatenateGenericAlias(origin, parameters, _typevar_types=(TypeVar, ParamSpec), _paramspec_tvars=True) else: - concatenate = _ConcatenateGenericAlias(origin, parameters) - if parameters[-1] is not _EllipsisDummy: - return concatenate - # Remove dummy again - concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ... - for p in concatenate.__args__) - concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__ - if p is not _EllipsisDummy) - return concatenate + return _ConcatenateGenericAlias(origin, parameters) # <=3.10 @@ -2197,57 +1852,7 @@ def Concatenate(self, parameters): return _concatenate_getitem(self, parameters) -# 3.10+ -if hasattr(typing, 'TypeGuard'): - TypeGuard = typing.TypeGuard -# 3.9 -else: - @_ExtensionsSpecialForm - def TypeGuard(self, parameters): - """Special typing form used to annotate the return type of a user-defined - type guard function. ``TypeGuard`` only accepts a single type argument. - At runtime, functions marked this way should return a boolean. - - ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static - type checkers to determine a more precise type of an expression within a - program's code flow. Usually type narrowing is done by analyzing - conditional code flow and applying the narrowing to a block of code. The - conditional expression here is sometimes referred to as a "type guard". - - Sometimes it would be convenient to use a user-defined boolean function - as a type guard. Such a function should use ``TypeGuard[...]`` as its - return type to alert static type checkers to this intention. - - Using ``-> TypeGuard`` tells the static type checker that for a given - function: - - 1. The return value is a boolean. - 2. If the return value is ``True``, the type of its argument - is the type inside ``TypeGuard``. - - For example:: - - def is_str(val: Union[str, float]): - # "isinstance" type guard - if isinstance(val, str): - # Type of ``val`` is narrowed to ``str`` - ... - else: - # Else, type of ``val`` is narrowed to ``float``. - ... - - Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower - form of ``TypeA`` (it can even be a wider form) and this may lead to - type-unsafe results. The main reason is to allow for things like - narrowing ``List[object]`` to ``List[str]`` even though the latter is not - a subtype of the former, since ``List`` is invariant. The responsibility of - writing type-safe type guards is left to the user. - - ``TypeGuard`` also works with type variables. For more information, see - PEP 647 (User-Defined Type Guards). - """ - item = typing._type_check(parameters, f'{self} accepts only a single type.') - return typing._GenericAlias(self, (item,)) +TypeGuard = typing.TypeGuard # 3.13+ @@ -3763,7 +3368,6 @@ def _check_single_param(self, param, recursion=0): return ... if param is None: return None - # Note in <= 3.9 _ConcatenateGenericAlias inherits from list if isinstance(param, list) and recursion == 0: return [self._check_single_param(arg, recursion+1) for arg in param] From ea6e4d616f58a2f5d42a7cb851282beb2971325f Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Fri, 27 Nov 2026 00:40:38 +0000 Subject: [PATCH 8/8] More --- src/test_typing_extensions.py | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/src/test_typing_extensions.py b/src/test_typing_extensions.py index 08849add..64472bee 100644 --- a/src/test_typing_extensions.py +++ b/src/test_typing_extensions.py @@ -150,10 +150,6 @@ is typing_extensions.TypeVarTuple ) -# https://github.com/python/cpython/pull/27017 was backported into some 3.9 and 3.10 -# versions, but not all -HAS_FORWARD_MODULE = "module" in inspect.signature(typing._type_check).parameters - skip_if_py313_beta_1 = skipIf( sys.version_info[:5] == (3, 13, 0, 'beta', 1), "Bugfixes will be released in 3.13.0b2" @@ -1916,18 +1912,11 @@ class C(Generic[T]): pass self.assertEqual(get_args(Callable), ()) self.assertEqual(get_args(list[int]), (int,)) self.assertEqual(get_args(list), ()) - # Support Python versions with and without the fix for - # https://bugs.python.org/issue42195 - # The first variant is for 3.9.2+, the second for 3.9.0 and 1 - self.assertIn(get_args(collections.abc.Callable[[int], str]), - (([int], str), ([[int]], str))) - self.assertIn(get_args(collections.abc.Callable[[], str]), - (([], str), ([[]], str))) + self.assertEqual(get_args(collections.abc.Callable[[int], str]), ([int], str)) + self.assertEqual(get_args(collections.abc.Callable[[], str]), ([], str)) self.assertEqual(get_args(collections.abc.Callable[..., str]), (..., str)) P = ParamSpec('P') - # In 3.9 we use typing_extensions's hacky implementation - # of ParamSpec, which gets incorrectly wrapped in a list - self.assertIn(get_args(Callable[P, int]), [(P, int), ([P], int)]) + self.assertEqual(get_args(Callable[P, int]), (P, int)) self.assertEqual(get_args(Required[int]), (int,)) self.assertEqual(get_args(NotRequired[int]), (int,)) self.assertEqual(get_args(Unpack[Ts]), (Ts,)) @@ -4789,7 +4778,6 @@ class PointDict3D(PointDict2D, total=False): assert is_typeddict(PointDict2D) is True assert is_typeddict(PointDict3D) is True - @skipUnless(HAS_FORWARD_MODULE, "ForwardRef.__forward_module__ was added in 3.9.7") def test_get_type_hints_cross_module_subclass(self): self.assertNotIn("_DoNotImport", globals()) self.assertEqual( @@ -9501,9 +9489,6 @@ class Gen[Tx]: evaluate_forward_ref(typing.ForwardRef("alias"), owner=Gen, locals={"alias": str}), str ) - @skipUnless( - HAS_FORWARD_MODULE, "Needs module 'forward' to test forward references" - ) def test_fwdref_with_module(self): self.assertIs( evaluate_forward_ref(typing.ForwardRef("Counter", module="collections")), collections.Counter @@ -9519,8 +9504,7 @@ def test_fwdref_with_module(self): def test_fwdref_to_builtin(self): self.assertIs(evaluate_forward_ref(typing.ForwardRef("int")), int) - if HAS_FORWARD_MODULE: - self.assertIs(evaluate_forward_ref(typing.ForwardRef("int", module="collections")), int) + self.assertIs(evaluate_forward_ref(typing.ForwardRef("int", module="collections")), int) self.assertIs(evaluate_forward_ref(typing.ForwardRef("int"), owner=str), int) # builtins are still searched with explicit globals