Tricks for coaxing PyCharm into inferring generic python type arguments in callables?

Viewed 34

I'm working on some code where functions get passed around a lot to other functions, and I'm trying to get PyCharm to help me get all the argument types right at "compile time" (or "IDE time" or whatever this is called). Unfortunately, I don't seem to be able to get very far. For example, PyCharm is perfectly happy with this code:

def plus_one(x: int) -> int:
    return x+1


map(plus_one, [1])
map(plus_one, ["aaa"])  # The error here could be spotted at "IDE time"

Even if I write my own version of map and type-hint it, PyCharm still doesn't complain:

from typing import List, Callable, TypeVar

def plus_one(x: int) -> int:
    return x+1
    

V = TypeVar("V")
W = TypeVar("W")
    

def map_list(f: Callable[[V], W], x: List[V]) -> List[W]:
    return [f(y) for y in x]


map_list(plus_one, [1])
map_list(plus_one, ["aaa"])

Is there any way to get PyCharm to be more aggressive about flagging type errors here?

0 Answers
Related