Skip to content

builtins.filter support for PEP 647 TypeGuard #2768

@Jasha10

Description

@Jasha10

Is your feature request related to a problem? Please describe.
Currently it seems that pyright does not support passing a type guard function as the first argument to the builtin filter function.
Here is an example:

# tmp.py
from typing import Iterable, Optional, TypeGuard


def is_not_none(x: Optional[int]) -> TypeGuard[int]:
    return x is not None

generate_optional: Iterable[Optional[int]] = (x if x % 2 == 0 else None for x in range(100))
list_optional: list[Optional[int]] = [0, None, 1, None, 2]
generate_ints: Iterable[int] = filter(is_not_none, list_optional)
$ pyright tmp.py
...
  /home/jasha10/tmp.py:9:32 - error: Expression of type "filter[int | None]" cannot be assigned to declared type "Iterable[int]"
    TypeVar "_T_co@Iterable" is covariant
      Type "int | None" cannot be assigned to type "int"
        Type "None" cannot be assigned to type "int" (reportGeneralTypeIssues)
1 error, 0 warnings, 0 infos

Describe the solution you'd like
It would be nice if type guard functions could be used with functional programming primitives such as filter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions