Skip to content

Commit c4baf4e

Browse files
committed
Extend special-case for context-based typevar inference in return position to typevar unions
1 parent 6aec4b8 commit c4baf4e

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

mypy/checkexpr.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2013,7 +2013,11 @@ def infer_function_type_arguments_using_context(
20132013
# variables in an expression are inferred at the same time.
20142014
# (And this is hard, also we need to be careful with lambdas that require
20152015
# two passes.)
2016-
if isinstance(ret_type, TypeVarType):
2016+
if (
2017+
isinstance(ret_type, TypeVarType)
2018+
or isinstance(ret_type, UnionType)
2019+
and all(isinstance(u, TypeVarType) for u in ret_type.items)
2020+
):
20172021
# Another special case: the return type is a type variable. If it's unrestricted,
20182022
# we could infer a too general type for the type variable if we use context,
20192023
# and this could result in confusing and spurious type errors elsewhere.

test-data/unit/check-inference-context.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1495,3 +1495,18 @@ def g(b: Optional[str]) -> None:
14951495
z: Callable[[], str] = lambda: reveal_type(b) # N: Revealed type is "builtins.str"
14961496
f2(lambda: reveal_type(b)) # N: Revealed type is "builtins.str"
14971497
lambda: reveal_type(b) # N: Revealed type is "builtins.str"
1498+
1499+
[case testInferenceContextReturningTypeVarUnion]
1500+
from collections.abc import Callable, Iterable
1501+
from typing import TypeVar, Union
1502+
1503+
_T1 = TypeVar("_T1")
1504+
_T2 = TypeVar("_T2")
1505+
1506+
def mymin(
1507+
iterable: Iterable[_T1], /, *, key: Callable[[_T1], int], default: _T2
1508+
) -> Union[_T1, _T2]: ...
1509+
1510+
def check(paths: Iterable[str], key: Callable[[str], int]) -> Union[str, None]:
1511+
return mymin(paths, key=key, default=None)
1512+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)