Skip to content

filter does not narrow TypeVar used in TypeGuard signature #12996

Open
@Jasha10

Description

@Jasha10

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 #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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions