Skip to content

Commit 8813968

Browse files
ilevkivskyiJukkaL
authored andcommitted
Fix type narrowing in lambda expressions (#16407)
Fixes #4297 Fix is straightforward: without properly pushing lambda expression on the stack, the previous fix @JukkaL added for nested functions doesn't work for lambdas (it thinks that we are at global scope).
1 parent 681e54c commit 8813968

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

mypy/checkexpr.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -5195,7 +5195,8 @@ def visit_lambda_expr(self, e: LambdaExpr) -> Type:
51955195
else:
51965196
# Type context available.
51975197
self.chk.return_types.append(inferred_type.ret_type)
5198-
self.chk.check_func_item(e, type_override=type_override)
5198+
with self.chk.tscope.function_scope(e):
5199+
self.chk.check_func_item(e, type_override=type_override)
51995200
if not self.chk.has_type(e.expr()):
52005201
# TODO: return expression must be accepted before exiting function scope.
52015202
self.accept(e.expr(), allow_none_return=True)

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

+13
Original file line numberDiff line numberDiff line change
@@ -1482,3 +1482,16 @@ b: Any
14821482
i = i if isinstance(i, int) else b
14831483
reveal_type(i) # N: Revealed type is "Union[Any, builtins.int]"
14841484
[builtins fixtures/isinstance.pyi]
1485+
1486+
[case testLambdaInferenceUsesNarrowedTypes]
1487+
from typing import Optional, Callable
1488+
1489+
def f1(key: Callable[[], str]) -> None: ...
1490+
def f2(key: object) -> None: ...
1491+
1492+
def g(b: Optional[str]) -> None:
1493+
if b:
1494+
f1(lambda: reveal_type(b)) # N: Revealed type is "builtins.str"
1495+
z: Callable[[], str] = lambda: reveal_type(b) # N: Revealed type is "builtins.str"
1496+
f2(lambda: reveal_type(b)) # N: Revealed type is "builtins.str"
1497+
lambda: reveal_type(b) # N: Revealed type is "builtins.str"

0 commit comments

Comments
 (0)