Skip to content

Commit bbee4e4

Browse files
committed
Apply TypeVar defaults (functions)
1 parent 10da8e7 commit bbee4e4

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

mypy/applytype.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
TypeVarLikeType,
1818
TypeVarTupleType,
1919
TypeVarType,
20+
UninhabitedType,
2021
UnpackType,
2122
get_proper_type,
2223
)
@@ -102,7 +103,9 @@ def apply_generic_arguments(
102103
target_type = get_target_type(
103104
tvar, type, callable, report_incompatible_typevar_value, context, skip_unsatisfied
104105
)
105-
if target_type is not None:
106+
if isinstance(target_type, UninhabitedType) and tvar.has_default():
107+
id_to_type[tvar.id] = tvar.default
108+
elif target_type is not None:
106109
id_to_type[tvar.id] = target_type
107110

108111
param_spec = callable.param_spec()

test-data/unit/check-typevar-defaults.test

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,27 @@ Ts1 = TypeVarTuple("Ts1", default=2) # E: TypeVarTuple "default" must be a type
7171
Ts2 = TypeVarTuple("Ts2", default=int) # E: The default argument to TypeVarTuple must be an Unpacked tuple
7272
Ts3 = TypeVarTuple("Ts3", default=Tuple[int]) # E: The default argument to TypeVarTuple must be an Unpacked tuple
7373
[builtins fixtures/tuple.pyi]
74+
75+
[case testTypeVarDefaultsFunctions]
76+
from typing import TypeVar, ParamSpec, List, Union, Callable, Tuple
77+
from typing_extensions import TypeVarTuple, Unpack
78+
79+
T1 = TypeVar("T1", default=str)
80+
P1 = ParamSpec("P1", default=(int, str))
81+
Ts1 = TypeVarTuple("Ts1", default=Unpack[Tuple[int, str]])
82+
83+
def callback1(x: str) -> None: ...
84+
85+
def func1(x: Union[int, T1]) -> List[T1]: ...
86+
reveal_type(func1(2)) # N: Revealed type is "builtins.list[builtins.str]"
87+
reveal_type(func1(2.1)) # N: Revealed type is "builtins.list[builtins.float]"
88+
89+
def func2(x: Union[int, Callable[P1, None]]) -> Callable[P1, None]: ...
90+
91+
reveal_type(func2(callback1)) # N: Revealed type is "def (x: builtins.str)"
92+
reveal_type(func2(2)) # N: Revealed type is "def (builtins.int, builtins.str)"
93+
94+
def func3(x: Union[int, Callable[[Unpack[Ts1]], None]]) -> Tuple[Unpack[Ts1]]: ...
95+
# reveal_type(func3(callback1)) # Revealed type is "builtins.tuple[str]" # TODO
96+
# reveal_type(func3(2)) # Revealed type is "builtins.tuple[builtins.int, builtins.str]" # TODO
97+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)