Skip to content

Improve handling of "lambda: None" #1557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 15, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -1347,6 +1347,11 @@ def visit_func_expr(self, e: FuncExpr) -> Type:
if e.expr() not in self.chk.type_map:
self.accept(e.expr())
ret_type = self.chk.type_map[e.expr()]
if isinstance(ret_type, NoneTyp):
# For "lambda ...: None", just use type from the context.
# Important when the context is Callable[..., None] which
# really means Void. See #1425.
return inferred_type
return replace_callable_return_type(inferred_type, ret_type)

def infer_lambda_type_using_context(self, e: FuncExpr) -> CallableType:
Expand Down
7 changes: 7 additions & 0 deletions test-data/unit/check-inference-context.test
Original file line number Diff line number Diff line change
Expand Up @@ -611,6 +611,13 @@ T = TypeVar('T')
def foo(arg: Callable[..., T]) -> None: pass
foo(lambda: 1)

[case testLambdaNoneInContext]
from typing import Callable
def f(x: Callable[[], None]) -> None: pass
def g(x: Callable[[], int]) -> None: pass
f(lambda: None)
g(lambda: None)


-- Overloads + generic functions
-- -----------------------------
Expand Down
11 changes: 11 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -1041,6 +1041,17 @@ y = f(lambda x: x, 1) # Fail
main:4: error: Cannot infer type argument 1 of "f"
main:4: error: Argument 2 to "f" has incompatible type "int"; expected "str"

[case testInferLambdaNone]
from typing import Callable
def f(x: Callable[[], None]) -> None: pass
def g(x: Callable[[], int]) -> None: pass
a = lambda: None
f(a) # E: Argument 1 to "f" has incompatible type Callable[[], None]; expected Callable[[], None]
g(a)
b = lambda: None # type: Callable[[], None]
f(b)
g(b) # E: Argument 1 to "g" has incompatible type Callable[[], None]; expected Callable[[], int]


-- Boolean operators
-- -----------------
Expand Down