Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mypy error when reshaping an array with a list of tuples

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading