Skip to content

Commit 2736f0b

Browse files
authored
Merge pull request #23800 from meeseeksmachine/auto-backport-of-pr-23785-on-v3.6.x
Backport PR #23785 on branch v3.6.x (FIX: ensure type stability for missing cmaps in `set_cmap`)
2 parents 855a6a1 + 99404df commit 2736f0b

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)