KEMBAR78
Do not auto-infer `TypeGuard` return type for `lambda`, refs #9927 by sobolevn · Pull Request #11417 · python/mypy · GitHub
Skip to content

Conversation

sobolevn
Copy link
Member

@sobolevn sobolevn commented Oct 31, 2021

Here's what was happening in this example:

from typing import Callable, Iterable, Iterator, List, Optional, TypeVar

T = TypeVar("T")
R = TypeVar("R")

def filter(f: Callable[[T], TypeGuard[R]], it: Iterable[T]) -> Iterator[R]: ...

a: List[Optional[int]]
bb = filter(lambda x: x is not None, a)
reveal_type(bb)  # error, actually it is now: Revealed type is "typing.Iterator[R`2]"

Mypy uses special logic in infer_lambda_type_using_context to infer lambda type args and return type. Basically, it just returns the current callable context type. Which is Callable[[T], TypeGuard[R]] in our case.

But, now I've limited this function to ignore contexts with TypeGuard. Because I believe that TypeGuard must always be explicit.

After this change Mypy works correctly:

» mypy out/ex.py --show-traceback
out/ex.py:13: error: Argument 1 to "filter" has incompatible type "Callable[[Any], bool]"; expected "Callable[[Optional[int]], TypeGuard[bool]]"
out/ex.py:14: note: Revealed type is "typing.Iterator[builtins.bool*]"
Found 1 error in 1 file (checked 1 source file)

Because we don't allow bool return type where TypeGuard is expected after #11314

The test from @gvanrossum that used to be skipped now passes 🎉

Closes #9927

@sobolevn
Copy link
Member Author

sobolevn commented Oct 31, 2021

One might notice that it still reveals out/ex.py:14: note: Revealed type is "typing.Iterator[builtins.bool*]", but this a completely different issue. This is how TypeGuard behaves for now. I can fix this later.

@hauntsaninja hauntsaninja merged commit 68047f9 into python:master Oct 31, 2021
@hauntsaninja
Copy link
Collaborator

Thank you!!

tushar-deepsource pushed a commit to DeepSourceCorp/mypy that referenced this pull request Jan 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

PEP 647 support mishandles higher-order functions

2 participants