dshin
dshin

Reputation: 2398

Typing with built-in map function

My IDE (PyCharm) is failing to auto-complete the following:

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

Is this a problem with my IDE, or is typing not compatible with map?

Whatever the answer, I tried to fix by wrapping 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

Again, is this a problem with my IDE, or are my expectations of the typing module incorrect?

Upvotes: 2

Views: 1863

Answers (1)

MSeifert
MSeifert

Reputation: 152647

The problem is that map returns an iterator and you can't index ([0]) iterators. When you cast the map to a list then PyCharm recognizes the type:

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].

Screenshot:

enter image description here

However, it seems like PyCharm can deduce the type for your function even without any type hints (in this case).

Upvotes: 3

Related Questions