I have a python module that looks as following:
import numpy as np
def test(order: str = 'C') -> np.ndarray:
return np.array([1,2,3]).reshape((1,2), order = order)
evaluating this with mypy returns the error and notes
error: No overload variant of "reshape" of "_ArrayOrScalarCommon" matches argument types "Tuple[int, int]", "str"
note: Possible overload variants:
note: def reshape(self, Sequence[int], *, order: Union[Literal['A'], Literal['C'], Literal['F'], None] = ...) -> ndarray
note: def reshape(self, *shape: int, order: Union[Literal['A'], Literal['C'], Literal['F'], None] = ...) -> ndarray
Substituting the section order = order in the function call with order = 'C' stops this error from occuring. Why is it a problem for mypy if I choose to pass this parameter as a function argument?
CodePudding user response:
test(order: str = 'C')
only sets the default value of parameter C
but you can still call it with any str
. For instance test('X')
is
correctly typed. But this causes test
to call reshape
with
order='X'
which is wrong and this is why mypy complains and this is
a good thing.
So the problem lies in the type definition of order
. You can change
it match the reshape
signature, and mypy is happy with it:
import typing as tp
import numpy as np
def test(order: tp.Optional[tp.Literal['A', 'C', 'F']] = 'C') -> np.ndarray:
return np.array([1,2,3]).reshape((1,2), order = order)
test('C') # ok
test('X') # mypy error