Skip to content

Commit 139ac68

Browse files
[3.14] Address invalid inputs of TypeAliasType (#477)
Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent 82d512a commit 139ac68

File tree

3 files changed

+101
-1
lines changed

3 files changed

+101
-1
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ aliases that have a `Concatenate` special form as their argument.
2323
`Ellipsis` as an argument. Patch by [Daraan](https://github.com/Daraan).
2424
- Fix error in subscription of `Unpack` aliases causing nested Unpacks
2525
to not be resolved correctly. Patch by [Daraan](https://github.com/Daraan).
26+
- Backport of CPython PR [#124795](https://github.com/python/cpython/pull/124795)
27+
and fix that `TypeAliasType` not raising an error on non-tupple inputs for `type_params`.
28+
Patch by [Daraan](https://github.com/Daraan).
2629

2730
# Release 4.12.2 (June 7, 2024)
2831

src/test_typing_extensions.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6192,6 +6192,10 @@ def test_typing_extensions_defers_when_possible(self):
61926192
'AsyncGenerator', 'ContextManager', 'AsyncContextManager',
61936193
'ParamSpec', 'TypeVar', 'TypeVarTuple', 'get_type_hints',
61946194
}
6195+
if sys.version_info < (3, 14):
6196+
exclude |= {
6197+
'TypeAliasType'
6198+
}
61956199
if not typing_extensions._PEP_728_IMPLEMENTED:
61966200
exclude |= {'TypedDict', 'is_typeddict'}
61976201
for item in typing_extensions.__all__:
@@ -7402,6 +7406,80 @@ def test_no_instance_subclassing(self):
74027406
class MyAlias(TypeAliasType):
74037407
pass
74047408

7409+
def test_type_var_compatibility(self):
7410+
# Regression test to assure compatibility with typing variants
7411+
typingT = typing.TypeVar('typingT')
7412+
T1 = TypeAliasType("TypingTypeVar", ..., type_params=(typingT,))
7413+
self.assertEqual(T1.__type_params__, (typingT,))
7414+
7415+
# Test typing_extensions backports
7416+
textT = TypeVar('textT')
7417+
T2 = TypeAliasType("TypingExtTypeVar", ..., type_params=(textT,))
7418+
self.assertEqual(T2.__type_params__, (textT,))
7419+
7420+
textP = ParamSpec("textP")
7421+
T3 = TypeAliasType("TypingExtParamSpec", ..., type_params=(textP,))
7422+
self.assertEqual(T3.__type_params__, (textP,))
7423+
7424+
textTs = TypeVarTuple("textTs")
7425+
T4 = TypeAliasType("TypingExtTypeVarTuple", ..., type_params=(textTs,))
7426+
self.assertEqual(T4.__type_params__, (textTs,))
7427+
7428+
@skipUnless(TYPING_3_10_0, "typing.ParamSpec is not available before 3.10")
7429+
def test_param_spec_compatibility(self):
7430+
# Regression test to assure compatibility with typing variant
7431+
typingP = typing.ParamSpec("typingP")
7432+
T5 = TypeAliasType("TypingParamSpec", ..., type_params=(typingP,))
7433+
self.assertEqual(T5.__type_params__, (typingP,))
7434+
7435+
@skipUnless(TYPING_3_12_0, "typing.TypeVarTuple is not available before 3.12")
7436+
def test_type_var_tuple_compatibility(self):
7437+
# Regression test to assure compatibility with typing variant
7438+
typingTs = typing.TypeVarTuple("typingTs")
7439+
T6 = TypeAliasType("TypingTypeVarTuple", ..., type_params=(typingTs,))
7440+
self.assertEqual(T6.__type_params__, (typingTs,))
7441+
7442+
def test_type_params_possibilities(self):
7443+
T = TypeVar('T')
7444+
# Test not a tuple
7445+
with self.assertRaisesRegex(TypeError, "type_params must be a tuple"):
7446+
TypeAliasType("InvalidTypeParams", List[T], type_params=[T])
7447+
7448+
# Test default order and other invalid inputs
7449+
T_default = TypeVar('T_default', default=int)
7450+
Ts = TypeVarTuple('Ts')
7451+
Ts_default = TypeVarTuple('Ts_default', default=Unpack[Tuple[str, int]])
7452+
P = ParamSpec('P')
7453+
P_default = ParamSpec('P_default', default=[str, int])
7454+
7455+
# NOTE: PEP 696 states: "TypeVars with defaults cannot immediately follow TypeVarTuples"
7456+
# this is currently not enforced for the type statement and is not tested.
7457+
# PEP 695: Double usage of the same name is also not enforced and not tested.
7458+
valid_cases = [
7459+
(T, P, Ts),
7460+
(T, Ts_default),
7461+
(P_default, T_default),
7462+
(P, T_default, Ts_default),
7463+
(T_default, P_default, Ts_default),
7464+
]
7465+
invalid_cases = [
7466+
((T_default, T), f"non-default type parameter {T!r} follows default"),
7467+
((P_default, P), f"non-default type parameter {P!r} follows default"),
7468+
((Ts_default, T), f"non-default type parameter {T!r} follows default"),
7469+
# Only type params are accepted
7470+
((1,), "Expected a type param, got 1"),
7471+
((str,), f"Expected a type param, got {str!r}"),
7472+
# Unpack is not a TypeVar but isinstance(Unpack[Ts], TypeVar) is True in Python < 3.12
7473+
((Unpack[Ts],), f"Expected a type param, got {re.escape(repr(Unpack[Ts]))}"),
7474+
]
7475+
7476+
for case in valid_cases:
7477+
with self.subTest(type_params=case):
7478+
TypeAliasType("OkCase", List[T], type_params=case)
7479+
for case, msg in invalid_cases:
7480+
with self.subTest(type_params=case):
7481+
with self.assertRaisesRegex(TypeError, msg):
7482+
TypeAliasType("InvalidCase", List[T], type_params=case)
74057483

74067484
class DocTests(BaseTestCase):
74077485
def test_annotation(self):

src/typing_extensions.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3528,8 +3528,9 @@ def __ror__(self, other):
35283528
return typing.Union[other, self]
35293529

35303530

3531-
if hasattr(typing, "TypeAliasType"):
3531+
if sys.version_info >= (3, 14):
35323532
TypeAliasType = typing.TypeAliasType
3533+
# 3.8-3.13
35333534
else:
35343535
def _is_unionable(obj):
35353536
"""Corresponds to is_unionable() in unionobject.c in CPython."""
@@ -3602,11 +3603,29 @@ class TypeAliasType:
36023603
def __init__(self, name: str, value, *, type_params=()):
36033604
if not isinstance(name, str):
36043605
raise TypeError("TypeAliasType name must be a string")
3606+
if not isinstance(type_params, tuple):
3607+
raise TypeError("type_params must be a tuple")
36053608
self.__value__ = value
36063609
self.__type_params__ = type_params
36073610

3611+
default_value_encountered = False
36083612
parameters = []
36093613
for type_param in type_params:
3614+
if (
3615+
not isinstance(type_param, (TypeVar, TypeVarTuple, ParamSpec))
3616+
# 3.8-3.11
3617+
# Unpack Backport passes isinstance(type_param, TypeVar)
3618+
or _is_unpack(type_param)
3619+
):
3620+
raise TypeError(f"Expected a type param, got {type_param!r}")
3621+
has_default = (
3622+
getattr(type_param, '__default__', NoDefault) is not NoDefault
3623+
)
3624+
if default_value_encountered and not has_default:
3625+
raise TypeError(f'non-default type parameter {type_param!r}'
3626+
' follows default type parameter')
3627+
if has_default:
3628+
default_value_encountered = True
36103629
if isinstance(type_param, TypeVarTuple):
36113630
parameters.extend(type_param)
36123631
else:

0 commit comments

Comments
 (0)