From 568d2215f17432ef74f882e8c752e051e74eef82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20H=C3=B8xbro=20Hansen?= Date: Mon, 27 Mar 2023 09:05:10 +0200 Subject: [PATCH 1/3] Only register if cmap not in colormaps --- colorcet/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/colorcet/__init__.py b/colorcet/__init__.py index 9e6e8af..fc808a0 100644 --- a/colorcet/__init__.py +++ b/colorcet/__init__.py @@ -62,7 +62,10 @@ def __setattr__(self, name, value): from matplotlib.colors import LinearSegmentedColormap, ListedColormap try: from matplotlib import colormaps - register_cmap = lambda name, cmap: colormaps.register(cmap, name=name) + def register_cmap(name, cmap): + if name not in colormaps or colormaps[name] != cmap: + # The last condition will raise an error + colormaps.register(cmap, name=name) except ImportError: # PendingDeprecationWarning from matplotlib 3.6 from matplotlib.cm import register_cmap From ca7ddf964f3f1b9c397b3be94d53ce8c849f9110 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20H=C3=B8xbro=20Hansen?= Date: Fri, 26 May 2023 15:46:50 +0200 Subject: [PATCH 2/3] Add unittest --- colorcet/tests/test_matplotlib.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/colorcet/tests/test_matplotlib.py b/colorcet/tests/test_matplotlib.py index 17645dc..e5eff4d 100644 --- a/colorcet/tests/test_matplotlib.py +++ b/colorcet/tests/test_matplotlib.py @@ -53,3 +53,25 @@ def test_get_cm(k, v): else: from matplotlib import colormaps assert colormaps['cet_' + k] == v + + +def test_register_cmap(): + import matplotlib as mpl + if Version(mpl.__version__) < Version("3.5"): + return + + cmap0 = cc.ListedColormap([[0, 0, 0], [1, 1, 1]]) + cmap1 = cc.ListedColormap([[0, 0, 0], [1, 1, 1]]) + cmap2 = cc.ListedColormap([[1, 1, 1], [0, 0, 0]]) + + name = "test_long_random_name_just_to_be_sure" + cc.register_cmap(name, cmap0) + + # Same values as before should pass + cc.register_cmap(name, cmap1) + + # Not same values should raise an Error + with pytest.raises( + ValueError, match=f'A colormap named "{name}" is already registered' + ): + cc.register_cmap(name, cmap2) From 8b982e33c5d82a5dc4347fc7124b709a94fc863c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20H=C3=B8xbro=20Hansen?= Date: Fri, 26 May 2023 16:05:35 +0200 Subject: [PATCH 3/3] Python 2 fix --- colorcet/tests/test_matplotlib.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/colorcet/tests/test_matplotlib.py b/colorcet/tests/test_matplotlib.py index e5eff4d..edbc21f 100644 --- a/colorcet/tests/test_matplotlib.py +++ b/colorcet/tests/test_matplotlib.py @@ -71,7 +71,6 @@ def test_register_cmap(): cc.register_cmap(name, cmap1) # Not same values should raise an Error - with pytest.raises( - ValueError, match=f'A colormap named "{name}" is already registered' - ): + msg = 'A colormap named "{}" is already registered'.format(name) + with pytest.raises(ValueError, match=msg): cc.register_cmap(name, cmap2)