Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: adding suggested names to ColormapRegistry missing key error #28115

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"""

from collections.abc import Mapping
import difflib
import functools

import numpy as np
Expand Down Expand Up @@ -88,7 +89,12 @@
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 = ""

Check warning on line 96 in lib/matplotlib/cm.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/cm.py#L96

Added line #L96 was not covered by tests
raise KeyError(f"{item!r} is not a known colormap name. {msg}") from None

def __iter__(self):
return iter(self._cmaps)
Expand Down
11 changes: 11 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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