Reputation: 2751
New to mypy and I'm having trouble finding the right way to get types working when filtering optionals from collections.
from typing import Optional, List
list1: List[Optional[int]] = [1, None, 3]
# This type is an error, filter can't even handle a list with optionals
list2: List[int] = list(filter(lambda n: n is not None, list1))
Should I be casting this? Should mypy be able to infer that None is filtered out now?
Upvotes: 6
Views: 2429
Reputation: 96181
Using typing.cast
should work, but I think the best solution here is to use a list comprehension.
The following code passes mypy for me:
from typing import Optional, List
list1: List[Optional[int]] = [1, None, 3]
list2: List[int] = [x for x in list1 if x is not None]
And in general, list comprehensions are the more idiomatic way of expressing mapping/filtering operations. (Guido actually wanted to remove map
/filter
in Python 3!)
Upvotes: 8