8000 Ensure we always infer a valid fallback type for lambda callables by Michael0x2a · Pull Request #13576 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Ensure we always infer a valid fallback type for lambda callables #13576

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
Sep 5, 2022
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
4 changes: 4 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 15 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
-- -----------------
Expand Down
0