Skip to content

Commit

Permalink
MNT: raise ValueError and TypeError rather than KeyError
Browse files Browse the repository at this point in the history
  • Loading branch information
tacaswell committed Oct 7, 2022
1 parent d0a240a commit 2f96205
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
15 changes: 8 additions & 7 deletions lib/matplotlib/cm.py
Expand Up @@ -202,10 +202,6 @@ def get_cmap(self, cmap):
Returns
-------
Colormap
Raises
------
KeyError
"""
# get the default color map
if cmap is None:
Expand All @@ -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,
Expand Down
6 changes: 4 additions & 2 deletions lib/matplotlib/tests/test_colors.py
Expand Up @@ -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"]
Expand All @@ -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"
Expand Down

0 comments on commit 2f96205

Please sign in to comment.