8000 Merge pull request #23785 from tacaswell/fix_cmap_missing_typestability · matplotlib/matplotlib@25b39d4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 25b39d4

Browse files
authored
Merge pull request #23785 from tacaswell/fix_cmap_missing_typestability
FIX: ensure type stability for missing cmaps in `set_cmap`
2 parents 747f843 + 1f7e0ef commit 25b39d4

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

lib/matplotlib/cm.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -701,6 +701,8 @@ def _ensure_cmap(cmap):
701701
"""
702702
if isinstance(cmap, colors.Colormap):
703703
return cmap
704-
return mpl.colormaps[
705-
cmap if cmap is not None else mpl.rcParams['image.cmap']
706-
]
704+
cmap_name = cmap if cmap is not None else mpl.rcParams["image.cmap"]
705+
# use check_in_list to ensure type stability of the exception raised by
706+
# the internal usage of this (ValueError vs KeyError)
707+
_api.check_in_list(sorted(_colormaps), cmap=cmap_name)
708+
return mpl.colormaps[cmap_name]

lib/matplotlib/tests/test_colors.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1543,3 +1543,11 @@ def test_color_sequences():
15431543
plt.color_sequences.unregister('rgb') # multiple unregisters are ok
15441544
with pytest.raises(ValueError, match="Cannot unregister builtin"):
15451545
plt.color_sequences.unregister('tab10')
1546+
1547+
1548+
def test_cm_set_cmap_error():
1549+
sm = cm.ScalarMappable()
1550+
# Pick a name we are pretty sure will never be a colormap name
1551+
bad_cmap = 'AardvarksAreAwkward'
1552+
with pytest.raises(ValueError, match=bad_cmap):
1553+
sm.set_cmap(bad_cmap)

0 commit comments

Comments
 (0)
0