首页 > 解决方案 > 诱使 PyCharm 在可调用对象中推断通用 Python 类型参数的技巧?

问题描述

我正在编写一些代码,其中函数被大量传递给其他函数,并且我试图让 PyC​​harm 帮助我在“编译时”(或“IDE 时间”或其他任何时候)正确获取所有参数类型称为)。不幸的是,我似乎无法走得很远。例如,PyCharm 对这段代码非常满意:

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"

即使我编写自己的版本map并输入提示,PyCharm 仍然不会抱怨:

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"])

有什么方法可以让 PyC​​harm 在此处更积极地标记类型错误?

标签: pythonpycharmtype-hinting

解决方案


推荐阅读