Skip to content

Commit 3f65a59

Browse files
committed
MNT: make sure we do not mutate input in Text.update
We take in a dictionary (called kwargs rather than collecting kwargs) which we mutate in the method. We pop bbox and fontproperties keys out of the user supplied dictionary (to make sure the precedence and default behaviors are correct) which is propagated back out to user code. This makes an internal copy of the dictionary before we mutate it. closes #18838
1 parent 74d6145 commit 3f65a59

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

lib/matplotlib/tests/test_text.py

+12
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,12 @@
88

99
import matplotlib as mpl
1010
from matplotlib.backend_bases import MouseEvent
11+
from matplotlib.font_manager import FontProperties
1112
import matplotlib.patches as mpatches
1213
import matplotlib.pyplot as plt
1314
import matplotlib.transforms as mtransforms
1415
from matplotlib.testing.decorators import check_figures_equal, image_comparison
16+
from matplotlib.text import Text
1517

1618

1719
needs_usetex = pytest.mark.skipif(
@@ -697,3 +699,13 @@ def test_transform_rotates_text():
697699
transform_rotates_text=True)
698700
result = text.get_rotation()
699701
assert_almost_equal(result, 30)
702+
703+
704+
def test_update_mutate_input():
705+
inp = dict(fontproperties=FontProperties(weight="bold"),
706+
bbox=None)
707+
cache = dict(inp)
708+
t = Text()
709+
t.update(inp)
710+
assert inp['fontproperties'] == cache['fontproperties']
711+
assert inp['bbox'] == cache['bbox']

lib/matplotlib/text.py

+2
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,8 @@ def __init__(self,
172172

173173
def update(self, kwargs):
174174
# docstring inherited
175+
# make a copy so we do not mutate user input!
176+
kwargs = dict(kwargs)
175177
sentinel = object() # bbox can be None, so use another sentinel.
176178
# Update fontproperties first, as it has lowest priority.
177179
fontproperties = kwargs.pop("fontproperties", sentinel)

0 commit comments

Comments
 (0)