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 4f8ece4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 13 deletions.
3 changes: 1 addition & 2 deletions doc/api/prev_api_changes/api_changes_3.6.0/deprecations.rst
Expand Up @@ -57,8 +57,7 @@ functions have been marked for pending deprecation:

**Added 3.6.1** Use `matplotlib.cm.ColormapRegistry.get_cmap` if you
have a string, `None` or a `matplotlib.colors.Colormap` object that you want
to convert to a `matplotlib.colors.Colormap` instance. Raises `KeyError`
rather than `ValueError` for missing strings.
to convert to a `matplotlib.colors.Colormap` instance.
- ``matplotlib.cm.register_cmap``; use `matplotlib.colormaps.register
<.ColormapRegistry.register>` instead
- ``matplotlib.cm.unregister_cmap``; use `matplotlib.colormaps.unregister
Expand Down
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 4f8ece4

Please sign in to comment.