Skip to content

Commit c1c8a13

Browse files
ddfisherJukkaL
authored andcommitted
Fix lambda inference with simple Union contexts (#2630)
1 parent 11303c2 commit c1c8a13

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

mypy/checkexpr.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1772,6 +1772,12 @@ def infer_lambda_type_using_context(self, e: FuncExpr) -> CallableType:
17721772
"""
17731773
# TODO also accept 'Any' context
17741774
ctx = self.chk.type_context[-1]
1775+
1776+
if isinstance(ctx, UnionType):
1777+
callables = [t for t in ctx.items if isinstance(t, CallableType)]
1778+
if len(callables) == 1:
1779+
ctx = callables[0]
1780+
17751781
if not ctx or not isinstance(ctx, CallableType):
17761782
return None
17771783

test-data/unit/check-optional.test

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,3 +518,10 @@ if x is not None:
518518
x.x = 1 # OK here
519519

520520
[builtins fixtures/ops.pyi]
521+
522+
[case testOptionalLambdaInference]
523+
from typing import Optional, Callable
524+
f = None # type: Optional[Callable[[int], None]]
525+
f = lambda x: None
526+
f(0)
527+
[builtins fixtures/function.pyi]

0 commit comments

Comments
 (0)