Skip to content

[Bug]: type-checking errors with mypy + matplotlib 3.8.0rc1 #26501

@neutrinoceros

Description

@neutrinoceros

Bug summary

In testing type-checking integration between matplotlib 3.8.0rc1 and cmyt, I found mypy flagged a couple errors that I think may be spurious ?

Here's a minimal reproducer of the issue I'm talking about.

Code for reproduction

# t.py , linted with `mypy t.py`
from matplotlib.colors import Colormap                                                                           
import numpy as np                                                                                               
def rgb_from_cmap(cmap: Colormap) -> np.ndarray:                                                                 
    RGBA = cmap(np.linspace(0, 1, 155))                                                                          
    RGB = RGBA[:, :3]                                                                                            
    return RGB

Actual outcome

t.py: note: In function "rgb_from_cmap":
t.py:5: error: No overload variant of "__getitem__" of "tuple" matches argument type "Tuple[slice, slice]"  [call-overload]
t.py:5: note: Possible overload variants:
t.py:5: note:     def __getitem__(self, SupportsIndex, /) -> float
t.py:5: note:     def __getitem__(self, slice, /) -> Tuple[float, ...]
t.py:6: error: Incompatible return value type (got "Union[float, ndarray[Any, Any]]", expected "ndarray[Any, Any]")  [return-value]
Found 2 errors in 1 file (checked 1 source file)

Expected outcome

no error. The second one is easy enough to handle in user code by returning np.asarray(RGB) (though I am not 100% sure that this should be necessary), but the first error really feels undesired to me;

Quoting from Colormap.__call__'s docstring:

   Returns
   -------
   Tuple of RGBA values if X is scalar, otherwise an array of
   RGBA values with a shape of ``X.shape + (4, )``.

it should be clear that the return value is necessarily an array with ndim >= 2 in my case ?
I think the problem is that the return type of this function is annotated as a union type

) -> tuple[float, float, float, float] | np.ndarray: ...

However it's not clear to me how to fix it.

Additional information

previous versions of matplotlib "type-checked" correctly (because everything was assumed to be Any !)

Operating system

ubuntu

Matplotlib Version

3.8.0rc1

Matplotlib Backend

N/A

Python version

3.11.4

Jupyter version

N/A

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions