I'm stuck with a strange issue with type annotations in Python. Even though I annotate a default argument (that is a container) or a container variable with the the correct type, mypy
seems to get confused when the container is empty or when I'm filtering out elements using comprehension. Here are my examples:
from typing import Set, Tuple
_Path_t = Tuple[int]
# default argument example
def my_func(key: str, bases: Tuple[int] = ()):
pass
Running mypy
on the above results in the following error:
error: Incompatible default for argument "bases" \
(default has type "Tuple[]", argument has type "Tuple[int]")
The other error when doing comprehension, can be replicated with the following:
seqs: Set[_Path_t] = {tuple(range(n, n + 5)) for n in range(2, 3)}
while seqs:
seqs = [seq[:-1] for seq in seqs if seq[:-1]]
For the assignment line above, mypy
emits the error:
error: Set comprehension has incompatible type Set[Tuple[int, ...]]; \
expected Set[Tuple[int]]
Which is absent in my original code, probably because I am not using range. The error for the variable reassignment inside the while
-loop is identical though:
error: Set comprehension has incompatible type Set[Tuple[]]; \
expected Set[Tuple[int]]
What am I missing?
Okay, I guess the problem stems from the fact that the container can be empty. This answer led me to the solution. In both cases, I need to annotate with Tuple[int, ...]
; in essence allowing for an empty container.