Expected type 'Union[ndarray, Iterable]' warning in Python instruction Expected type 'Union[ndarray, Iterable]' warning in Python instruction numpy numpy

Expected type 'Union[ndarray, Iterable]' warning in Python instruction


I'm guessing that PyCharm does not fully understand numpy. It looks and acts like valid Python:

Using my IDE, Ipython, I can do:

In [84]: n,k,l=3, .4, 1In [85]: v = np.transpose(np.cos(np.arange(0, n) * np.pi * k * l))In [86]: vOut[86]: array([ 1.        ,  0.30901699, -0.80901699])


These false positives happen a lot with numpy code in PyCharm. In a thread discussing this issue with JetBrains support, they say:

Almost any code written in reasonably elegant numpy style gets drowned in warning messages.

For arguments of your own functions you can write docstrings to let PyCharm know what type to expect. For a lot of numpy code however this will not be relevant. There are two solutions I found:

  1. Suppress the warnings per-line or per-function with the line # noinspection PyTypeChecker before the line or function where the warning occurs. See the official guide for more details on suppressing warnings
  2. Use type hinting as in this answer:

    transpose_arg = np.cos(np.arange(0, n) * np.pi * k * l)  # type: np.ndarrayv = np.transpose(transpose_arg)


To append to buzjwa's answer:

Option 3: Use mypy for type checking and manually add the 3rd party stub file created for numpy here

You will need to add this stub file to your internal python typeshed. Let us know how you get on!