diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index fba6caec4072..e4b50b87b1f2 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -4230,6 +4230,10 @@ def infer_lambda_type_using_context( callable_ctx = get_proper_type(replace_meta_vars(ctx, ErasedType())) assert isinstance(callable_ctx, CallableType) + # The callable_ctx may have a fallback of builtins.type if the context + # is a constructor -- but this fallback doesn't make sense for lambdas. + callable_ctx = callable_ctx.copy_modified(fallback=self.named_type("builtins.function")) + if callable_ctx.type_guard is not None: # Lambda's return type cannot be treated as a `TypeGuard`, # because it is implicit. And `TypeGuard`s must be explicit. diff --git a/test-data/unit/check-inference.test b/test-data/unit/check-inference.test index c09424138e49..1e6d947d6113 100644 --- a/test-data/unit/check-inference.test +++ b/test-data/unit/check-inference.test @@ -1276,6 +1276,21 @@ class A: def h(x: Callable[[], int]) -> None: pass +[case testLambdaJoinWithDynamicConstructor] +from typing import Any, Union + +class Wrapper: + def __init__(self, x: Any) -> None: ... + +def f(cond: bool) -> Any: + f = Wrapper if cond else lambda x: x + reveal_type(f) # N: Revealed type is "def (x: Any) -> Any" + return f(3) + +def g(cond: bool) -> Any: + f = lambda x: x if cond else Wrapper + reveal_type(f) # N: Revealed type is "def (x: Any) -> Any" + return f(3) -- Boolean operators -- -----------------