I've boiled down the code which I actually want to anotate to this minimal version:
def print_it(numbers_or_nones):
for i, number in enumerate(numbers_or_nones):
if number is None:
numbers_or_nones[i] = 0
print("NOOOO")
else:
print(number)
numbers = [1, 2, 3, 4]
print_it(numbers)
I want to annotate the parameter numbers_or_nones of print_it. It needs to be...
- ... a generic type where the elements are
Optional[int] - ... iterable
- ... support indexed assignment
What is the correct type for this case? Please note that it's not possible to change the type of numbers : List[int]. The only option I can see is to use typing.overload.
List
The simplest thing would be List[Optional[int]]. However, this gives:
error: Argument 1 to "print_it" has incompatible type "List[int]"; expected "List[Optional[int]]"
note: "List" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
note: Consider using "Sequence" instead, which is covariant
Sequence
Unsupported target for indexed assignment ("Sequence[Optional[int]]")
MutableSequence
error: Argument 1 to "print_it" has incompatible type "List[int]"; expected "MutableSequence[Optional[int]]"