2017-05-15 19 views
1

我的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模塊的預期不正確的?

回答

1

問題是,map返回一個迭代器,你不能索引([0])迭代器。當你施放的maplist然後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]. 

截圖:

enter image description here

然而,這似乎是PyCharm可以推斷出你的函數的類型,即使沒有任何類型的提示(在這種情況下)。

+0

哎呀,這很愚蠢。對不起,我應該嘗試運行一些實際的代碼,而不是嘗試自動完成。謝謝! – dshin

+0

@abccd ok!你真的困惑我:) – MSeifert