From f5d86f4af7430672b6352dba18ea48fb4150fb20 Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Sun, 21 Apr 2024 21:25:52 -0400 Subject: [PATCH 1/2] ENH: adding suggested names to ColormapRegistry missing key error difflib.get_close_match has been in the standard library from Python 2.1 --- lib/matplotlib/cm.py | 8 +++++++- lib/matplotlib/tests/test_colors.py | 11 +++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index c14973560ac3..47f5916eabc5 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 = "No known keys are close" + 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 From 9509d885079ed08c6f8d77705babdf194cb7209a Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Mon, 22 Apr 2024 21:56:30 -0400 Subject: [PATCH 2/2] MNT: Add no comment if no close match Maintains the status-quo Co-authored-by: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> --- lib/matplotlib/cm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 47f5916eabc5..d7957416f58c 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -93,7 +93,7 @@ def __getitem__(self, item): if len(best := difflib.get_close_matches(item, known, cutoff=.1)): msg = f"Did you mean one of {best}?" else: - msg = "No known keys are close" + msg = "" raise KeyError(f"{item!r} is not a known colormap name. {msg}") from None def __iter__(self): pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

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:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy