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

Only register if cmap not in colormaps #108

Merged
merged 3 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion colorcet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions colorcet/tests/test_matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,24 @@ 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
msg = 'A colormap named "{}" is already registered'.format(name)
with pytest.raises(ValueError, match=msg):
cc.register_cmap(name, cmap2)