`filter` does not narrow `TypeVar` used in `TypeGuard` signature
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Using filter with a TypeGuard, the TypeVar used in the TypeGuard signature is not properly narrowed.
To Reproduce
# tmp.py
from typing import Iterator, Optional, TypeVar
from typing_extensions import TypeGuard
T = TypeVar("T")
def is_not_none(x: Optional[T]) -> TypeGuard[T]:
return x is not None
maybe_ints: list[Optional[int]] = [1, None, 2]
ints: Iterator[int] = filter(is_not_none, maybe_ints)
$ mypy tmp.py
tmp.py:14: error: Argument 1 to "filter" has incompatible type "Callable[[Optional[T]], TypeGuard[T]]"; expected "Callable[[Optional[int]], TypeGuard[int]]"
Found 1 error in 1 file (checked 1 source file)
Expected Behavior
I wouldn't expect any error. Since the second argument to filter is typed as list[Optional[int]], mypy should narrow the TypeVar T appropriately.
Your Environment
- Mypy version used:
mypy 0.950 - Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10
This may be related to https://github.com/python/mypy/issues/12682. I decided to open a new ticket instead of commenting on that issue because the repro above feels different from the one reported on that issue.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the report with tmp.py and mypy 0.950 or the current version, focusing on filter with is_not_none and the TypeGuard TypeVar. Trace the type-checking path for filter callback inference and TypeGuard narrowing; done means the example type-checks and ints is accepted as Iterator[int].
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100