Skip to content

Commit 1f9317f

Browse files
authored
fix: fail check if not enough or too many types provided to TypeAliasType (#18308)
Fixes #18307 by failing a type alias call check if the number of positional arguments isn't exactly 2 (one for the type name as a literal string, one for the target type to alias). Before: ```python from typing_extensions import TypeAliasType T1 = TypeAliasType("T1", int, str) # Silently passes and uses `int` as the target type, should be an error T2 = TypeAliasType("T2") # Crashes ``` After: ```python T1 = TypeAliasType("T1", int, str) # E: Too many positional arguments for "TypeAliasType" T2 = TypeAliasType("T2") # E: Missing positional argument "value" in call to "TypeAliasType" ``` The error messages above are propagated from a check with the [`TypeAliasType` constructor definition from the stubs](https://github.com/python/typeshed/blob/bd728fbfae18395c37d9fd020e31b1d4f30c6136/stdlib/typing.pyi#L1041-L1044), so no further special-casing is necessary: ```python class TypeAliasType: def __init__( self, name: str, value: Any, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = () ) -> None: ... ```
1 parent 7d81f29 commit 1f9317f

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

mypy/semanal.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4157,8 +4157,12 @@ def check_type_alias_type_call(self, rvalue: Expression, *, name: str) -> TypeGu
41574157
names.append("typing.TypeAliasType")
41584158
if not refers_to_fullname(rvalue.callee, tuple(names)):
41594159
return False
4160+
if not self.check_typevarlike_name(rvalue, name, rvalue):
4161+
return False
4162+
if rvalue.arg_kinds.count(ARG_POS) != 2:
4163+
return False
41604164

4161-
return self.check_typevarlike_name(rvalue, name, rvalue)
4165+
return True
41624166

41634167
def analyze_type_alias_type_params(
41644168
self, rvalue: CallExpr

test-data/unit/check-type-aliases.test

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1105,6 +1105,10 @@ t1: T1 # E: Variable "__main__.T1" is not valid as a type \
11051105
T3 = TypeAliasType("T3", -1) # E: Invalid type: try using Literal[-1] instead?
11061106
t3: T3
11071107
reveal_type(t3) # N: Revealed type is "Any"
1108+
1109+
T4 = TypeAliasType("T4") # E: Missing positional argument "value" in call to "TypeAliasType"
1110+
T5 = TypeAliasType("T5", int, str) # E: Too many positional arguments for "TypeAliasType" \
1111+
# E: Argument 3 to "TypeAliasType" has incompatible type "Type[str]"; expected "Tuple[Union[TypeVar?, ParamSpec?, TypeVarTuple?], ...]"
11081112
[builtins fixtures/tuple.pyi]
11091113
[typing fixtures/typing-full.pyi]
11101114

0 commit comments

Comments
 (0)