From 76e087dbfc13cdd5950cf20472d72259bb897813 Mon Sep 17 00:00:00 2001 From: Eric Larson Date: Wed, 7 Dec 2022 13:17:10 -0500 Subject: [PATCH] BUG: Fix bug with mutable input modification --- lib/matplotlib/image.py | 3 +++ lib/matplotlib/tests/test_agg.py | 2 ++ lib/matplotlib/tests/test_image.py | 1 + 3 files changed, 6 insertions(+) diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 78e9237e1cb4..1b011a00721a 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -1653,6 +1653,9 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, rgba = sm.to_rgba(arr, bytes=True) if pil_kwargs is None: pil_kwargs = {} + else: + # we modify this below, so make a copy (don't modify caller's dict) + pil_kwargs = pil_kwargs.copy() pil_shape = (rgba.shape[1], rgba.shape[0]) image = PIL.Image.frombuffer( "RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1) diff --git a/lib/matplotlib/tests/test_agg.py b/lib/matplotlib/tests/test_agg.py index 68ec0c4fda3e..5285a24f01f6 100644 --- a/lib/matplotlib/tests/test_agg.py +++ b/lib/matplotlib/tests/test_agg.py @@ -254,9 +254,11 @@ def test_pil_kwargs_webp(): buf_small = io.BytesIO() pil_kwargs_low = {"quality": 1} plt.savefig(buf_small, format="webp", pil_kwargs=pil_kwargs_low) + assert len(pil_kwargs_low) == 1 buf_large = io.BytesIO() pil_kwargs_high = {"quality": 100} plt.savefig(buf_large, format="webp", pil_kwargs=pil_kwargs_high) + assert len(pil_kwargs_high) == 1 assert buf_large.getbuffer().nbytes > buf_small.getbuffer().nbytes diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index f10fb9dd97e6..07852881ebd8 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -249,6 +249,7 @@ def test_imsave_pil_kwargs_tiff(): buf = io.BytesIO() pil_kwargs = {"description": "test image"} plt.imsave(buf, [[0, 1], [2, 3]], format="tiff", pil_kwargs=pil_kwargs) + assert len(pil_kwargs) == 1 im = Image.open(buf) tags = {TAGS[k].name: v for k, v in im.tag_v2.items()} assert tags["ImageDescription"] == "test image"