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 a2dc64a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 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
13 changes: 9 additions & 4 deletions lib/matplotlib/tests/test_colors.py
Expand Up @@ -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"
Expand Down

0 comments on commit a2dc64a

Please sign in to comment.