使用内置地图功能打字

Typing with built-in map function

我的 IDE (PyCharm) 无法自动完成以下内容:

from typing import List, TypeVar

T = TypeVar('T')

def listify(x: T) -> List[T]:
    return [x]

str_list: List[str] = ['a', 'b']
listified = map(listify, str_list)
listified[0].<TAB>  # autocomplete fail, IDE fails to recognize this is a List

这是我的 IDE 的问题,还是 typingmap 不兼容?

无论答案如何,我都尝试通过包装 map:

来修复
from typing import Callable, Iterable, List, TypeVar

T = TypeVar('T')
U = TypeVar('U')

def listify(x: T) -> List[T]:
    return [x]

def univariate_map(func: Callable[[T], U], x: Iterable[T]) -> Iterable[U]:
    return map(func, x)  

str_list: List[str] = ['a', 'b']
listified = univariate_map(listify, str_list)
listified[0].<TAB>  # still fails to autocomplete

同样,这是我的 IDE 的问题,还是我对 typing 模块的期望不正确?

问题是 map returns 一个迭代器,你不能索引 ([0]) 个迭代器。当您将 map 转换为 list 时,PyCharm 识别类型:

from typing import List, TypeVar

T = TypeVar('T')

def listify(x: T) -> List[T]:
    return [x]

str_list: List[str] = ['a', 'b']
listified = list(map(listify, str_list))  # list is new here
listified[0].

截图:

但是,似乎 PyCharm 即使没有任何类型提示(在本例中)也可以推断出您的函数的类型。