Skip to content

Incorrect inference of Callable generic typing #5199

Description

@asottile
fromtypingimportCallablefromtypingimportIterablefromtypingimportListfromtypingimportOptionalfromtypingimportTypeVarclassC:
x: strT=TypeVar('T')
deff(i: Iterable[T], c: Callable[[T], bool]) ->Optional[T]:
forxini:
ifc(x):
returnxelse:
returnNonedefg(l: List[C], x: str) ->Optional[C]:
returnf(l, lambdad: 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:

fromtypingimportCallablefromtypingimportIterablefromtypingimportListfromtypingimportOptionalfromtypingimportTypeVarclassC:
x: strT=TypeVar('T')
deff(i: Iterable[T], c: Callable[[T], bool]) ->Optional[T]:
forxini:
ifc(x):
returnxelse:
returnNonedefg(l: List[C], x: str) ->Optional[C]:
defpred(d: C) ->bool:
returnd.x==xreturnf(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