diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index c14973560ac3..d7957416f58c 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -15,6 +15,7 @@ """ from collections.abc import Mapping +import difflib import functools import numpy as np @@ -88,7 +89,12 @@ def __getitem__(self, item): try: return self._cmaps[item].copy() except KeyError: - raise KeyError(f"{item!r} is not a known colormap name") from None + known = list(self._cmaps) + if len(best := difflib.get_close_matches(item, known, cutoff=.1)): + msg = f"Did you mean one of {best}?" + else: + msg = "" + raise KeyError(f"{item!r} is not a known colormap name. {msg}") from None def __iter__(self): return iter(self._cmaps) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 63f2d4f00399..74a1379af1ff 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -1697,3 +1697,14 @@ def test_to_rgba_array_none_color_with_alpha_param(): assert_array_equal( to_rgba_array(c, alpha), [[0., 0., 1., 1.], [0., 0., 0., 0.]] ) + + +def test_close_error_name(): + with pytest.raises(KeyError) as exinfo: + matplotlib.colormaps["grays"] + + msg = exinfo.value.args[0] + + assert "Grays" in msg + assert "gray" in msg + assert "gray_r" in msg
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: