From a2dc64a7cf68374e1447396de90e1490661bcbb0 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Fri, 7 Oct 2022 17:10:04 -0400 Subject: [PATCH] MNT: raise ValueError and TypeError rather than KeyError --- lib/matplotlib/cm.py | 15 ++++++++------- lib/matplotlib/tests/test_colors.py | 13 +++++++++---- 2 files changed, 17 insertions(+), 11 deletions(-) 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..86536ab17234 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -111,18 +111,23 @@ 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 + # check str, and Colormap pass assert cr.get_cmap('plasma') == cr["plasma"] assert cr.get_cmap(cr["magma"]) == cr["magma"] - # check default default + # check default assert cr.get_cmap(None) == cr[mpl.rcParams['image.cmap']] + + # check ValueError on bad name bad_cmap = 'AardvarksAreAwkward' - with pytest.raises(KeyError, match=bad_cmap): + with pytest.raises(ValueError, match=bad_cmap): cr.get_cmap(bad_cmap) + # check TypeError on bad type + with pytest.raises(TypeError, match='object'): + cr.get_cmap(object()) + def test_double_register_builtin_cmap(): name = "viridis"