'My error on: Value of type "Optional[ndarray[Any, dtype[Any]]]" is not indexable

I have the following code in Python:

    X, Y = np.meshgrid(np.arange(0, Z.shape[1], dtype=float), np.arange(0, Z.shape[0], dtype=float))
    
    # error 1
    Y = np.nanmax(Y) - Y + np.nanmin(Y) 
    
    # error 2
    X_cropped = X[p_ys : p_ys + p_height, p_xs : p_xs + p_width]
    Y_cropped = Y[p_ys : p_ys + p_height, p_xs : p_xs + p_width]

I got the following two errors when I tested the code with mypy in linting:

error 1:

error: Argument 1 has incompatible type "Optional[ndarray[Any, dtype[Any]]]"; expected "Union[_SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, int, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]]"

error 2:

Value of type "Optional[ndarray[Any, dtype[Any]]]" is not indexable

I guess that the errors may come from the incompatible Optional type. The code works as expected, but how can I avoid them when using mypy? Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source