python/mypy

Generic function type argument inference problem

JukkaL opened this issue · 5 comments

The type checker can't infer the type argument in the call to f below, even though there seems to be no reason why it shouldn't be able to do it:

from typing import List, TypeVar
T = TypeVar('T')
def f(a: List[T], b: List[T]) -> None: pass
x = ['']
f(x, [])  # Cannot infer type argument 1 of "f"

After #556 is done, this becomes more annoying.

This doesn't seem so easy to fix. We need to either make use of information learned from type checking the first argument to infer a type variable in the second argument (but what if the arguments were in the other order?) or be able to return a polymorphic type when type checking the second argument. I think the latter is easier and it's related to some other changes I want to make anyways (e.g. #1551), but it will require some reorganization.

Based on Reid's comment I'm moving this to 0.5.0 (or maybe even later?).

Is there some syntax to pass type arguments explicitly when Python cannot infer the types? I am looking for something like this: f[str](x, []). If not, is there an issue or document when this "explicit passing of type arguments" feature is tracked?

@earshinov I think the best recent issue to discuss allowing explicit type application for functions is #6073.