Mypy: Can't deduce an argument of type 1 from "map"
When trying to test the following code with mypy:
import itertools
from typing import Sequence, Union, List
DigitsSequence = Union[str, Sequence[Union[str, int]]]
def normalize_input(digits: DigitsSequence) -> List[str]:
try:
new_digits = list(map(str, digits)) # <- Line 17
if not all(map(str.isdecimal, new_digits)):
raise TypeError
except TypeError:
print("Digits must be an iterable containing strings.")
return []
return new_digits
mypy throws the following errors:
calculate.py:17: error: Cannot output argument of type 1 "map"
Why is this error occurring? How can I fix this?
Thank:)
source to share
As you already know, mypy depends on typeshed to stub out classes and functions in the Python standard library. I believe your problem is related to stubbing tigersmap
:
@overload
def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ...
And that the current state of mypy is such that its type inference is not unlimited. (The project also has over 600 open issues. )
I believe your problem may be related to issue # 1855 . I believe that this is the case because DigitsSequence = str
, and DigitsSequence = Sequence[int]
operate simultaneously, but DigitsSequence = Union[str, Sequence[int]]
- no.
Some workarounds:
-
Use a lambda expression instead:
new_digits = list(map(lambda s: str(s), digits))
-
Re-add the new variable:
any_digits = digits # type: Any new_digits = list(map(str, any_digits))
-
Tell mypy to ignore the line:
new_digits = list(map(str, digits)) # type: ignore
source to share