Mypy type compatible with list, tuple, range, and numpy.array?
Question:
The code
import numpy as np
def join(v:list, delim:str = ","):
""" join the elements of v using the given delimiter """
return delim.join(str(x) for x in v)
print(join([0,1,2,3]))
print(join((0,1,2,3)))
print(join(range(4)))
print(join(np.array(range(4))))
runs, but mypy only likes the first call to join
and says
x.py:8: error: Argument 1 to "join" has incompatible type "Tuple[int, int, int, int]"; expected "List[Any]" [arg-type]
x.py:9: error: Argument 1 to "join" has incompatible type "range"; expected "List[Any]" [arg-type]
x.py:10: error: Argument 1 to "join" has incompatible type "ndarray[Any, dtype[Any]]"; expected "List[Any]" [arg-type]
Found 3 errors in 1 file (checked 1 source file)
Is there a different type annotation for argument v
that will fix these errors?
Answers:
You can use Iterable
from the typing module (see documentation here)
The code
import numpy as np
def join(v:list, delim:str = ","):
""" join the elements of v using the given delimiter """
return delim.join(str(x) for x in v)
print(join([0,1,2,3]))
print(join((0,1,2,3)))
print(join(range(4)))
print(join(np.array(range(4))))
runs, but mypy only likes the first call to join
and says
x.py:8: error: Argument 1 to "join" has incompatible type "Tuple[int, int, int, int]"; expected "List[Any]" [arg-type]
x.py:9: error: Argument 1 to "join" has incompatible type "range"; expected "List[Any]" [arg-type]
x.py:10: error: Argument 1 to "join" has incompatible type "ndarray[Any, dtype[Any]]"; expected "List[Any]" [arg-type]
Found 3 errors in 1 file (checked 1 source file)
Is there a different type annotation for argument v
that will fix these errors?
You can use Iterable
from the typing module (see documentation here)