'how to make the mypy accept List[Optional[str]] as input arg for filter()?

I have these lines:

tags: List[Optional[str]] = [None, "adf"]
x: List[str] = list(filter(lambda x: x is not None, tags))

the mypy errors out Argument 2 to "filter" has incompatible type "List[Optional[str]]"; expected "Iterable[str]" Is there anyway to type hint the lambda?



Solution 1:[1]

I've run into the same issue and the workaround I used was to basically do a list comprehension to remove None, which in your case would be

x: List[str] = [t for t in tags if t is not None]

I know it's a little bit less pythonic and less readable than the filter approach you were trying to use, but it seems like this is what mypy would prefer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lau