diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 254efdd95fca..ec0d472992ef 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -202,10 +202,6 @@ def get_cmap(self, cmap): Returns ------- Colormap - - Raises - ------ - KeyError """ # get the default color map if cmap is None: @@ -214,9 +210,14 @@ def get_cmap(self, cmap): # if the user passed in a Colormap, simply return it if isinstance(cmap, colors.Colormap): return cmap - - # otherwise, it must be a string so look it up - return self[cmap] + if isinstance(cmap, str): + _api.check_in_list(sorted(_colormaps), cmap=cmap) + # otherwise, it must be a string so look it up + return self[cmap] + raise TypeError( + 'get_cmap expects None or an instance of a str or Colormap . ' + + f'you passed {cmap!r} of type {type(cmap)}' + ) # public access to the colormaps should be via `matplotlib.colormaps`. For now, diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 3b4a775c5379..846c3a514380 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -111,7 +111,6 @@ def test_register_cmap(): def test_colormaps_get_cmap(): cr = mpl.colormaps - new_cm = mcolors.ListedColormap(cr["viridis"].colors, name='v2') # check None, str, and Colormap pass assert cr.get_cmap('plasma') == cr["plasma"] @@ -120,9 +119,12 @@ def test_colormaps_get_cmap(): # check default default assert cr.get_cmap(None) == cr[mpl.rcParams['image.cmap']] bad_cmap = 'AardvarksAreAwkward' - with pytest.raises(KeyError, match=bad_cmap): + with pytest.raises(ValueError, match=bad_cmap): cr.get_cmap(bad_cmap) + with pytest.raises(TypeError, match='object'): + cr.get_cmap(object()) + def test_double_register_builtin_cmap(): name = "viridis"