Skip to content

Incorrect inference of Callable generic typing #5199

Closed
@asottile

Description

@asottile
from typing import Callable
from typing import Iterable
from typing import List
from typing import Optional
from typing import TypeVar


class C:
    x: str


T = TypeVar('T')


def f(i: Iterable[T], c: Callable[[T], bool]) -> Optional[T]:
    for x in i:
        if c(x):
            return x
    else:
        return None


def g(l: List[C], x: str) -> Optional[C]:
    return f(l, lambda d: d.x == x)
$ mypy test.py
test.py:24: error: Item "None" of "Optional[C]" has no attribute "x"
$ mypy --version
mypy 0.610

A little bit complicated, though I believe the lambda should be inferenced as Callable[[C], bool] though it appears to instead be inferenced as Callable[[Optional[C]], bool]

A related, less-lambda-y reproduction:

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


class C:
    x: str


T = TypeVar('T')


def f(i: Iterable[T], c: Callable[[T], bool]) -> Optional[T]:
    for x in i:
        if c(x):
            return x
    else:
        return None


def g(l: List[C], x: str) -> Optional[C]:
    def pred(d: C) -> bool:
        return d.x == x

    return f(l, pred)
$ mypy test2.py
test2.py:27: error: Argument 2 to "f" has incompatible type "Callable[[C], bool]"; expected "Callable[[Optional[C]], bool]"

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions