Skip to content

Replace sole use of maxdict by lru_cache. #22323

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

Merged
merged 2 commits into from
Jan 27, 2022
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
4 changes: 4 additions & 0 deletions doc/api/next_api_changes/deprecations/22323-GL.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
``matplotlib.cbook.maxdict`` is deprecated
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This class has been deprecated in favor of the standard library
``functools.lru_cache``.
1 change: 1 addition & 0 deletions lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,7 @@ def flatten(seq, scalarp=is_scalar_or_string):
yield from flatten(item, scalarp)


@_api.deprecated("3.6", alternative="functools.lru_cache")
class maxdict(dict):
"""
A dictionary with a maximum size.
Expand Down
7 changes: 7 additions & 0 deletions lib/matplotlib/tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,8 @@ def test_pdf_chars_beyond_bmp():

@needs_usetex
def test_metrics_cache():
mpl.text._get_text_metrics_with_cache_impl.cache_clear()

fig = plt.figure()
fig.text(.3, .5, "foo\nbar")
fig.text(.3, .5, "foo\nbar", usetex=True)
Expand All @@ -788,3 +790,8 @@ def call(*args, **kwargs):
# collision with the non-TeX string (drawn first here) whose metrics would
# get incorrectly reused by the first TeX string.
assert len(ys["foo"]) == len(ys["bar"]) == 1

info = mpl.text._get_text_metrics_with_cache_impl.cache_info()
# Every string gets a miss for the first layouting (extents), then a hit
# when drawing, but "foo\nbar" gets two hits as it's drawn twice.
assert info.hits > info.misses
43 changes: 21 additions & 22 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Classes for including text in a figure.
"""

import functools
import logging
import math
import numbers
Expand Down Expand Up @@ -89,6 +90,21 @@ def _get_textbox(text, renderer):
return x_box, y_box, w_box, h_box


def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):
"""Call ``renderer.get_text_width_height_descent``, caching the results."""
# Cached based on a copy of fontprop so that later in-place mutations of
# the passed-in argument do not mess up the cache.
return _get_text_metrics_with_cache_impl(
weakref.ref(renderer), text, fontprop.copy(), ismath, dpi)


@functools.lru_cache(4096)
def _get_text_metrics_with_cache_impl(
renderer_ref, text, fontprop, ismath, dpi):
# dpi is unused, but participates in cache invalidation (via the renderer).
return renderer_ref().get_text_width_height_descent(text, fontprop, ismath)


@docstring.interpd
@cbook._define_aliases({
"color": ["c"],
Expand All @@ -108,7 +124,6 @@ class Text(Artist):
"""Handle storing and drawing of text in window or data coordinates."""

zorder = 3
_cached = cbook.maxdict(50)

def __repr__(self):
return "Text(%s, %s, %s)" % (self._x, self._y, repr(self._text))
Expand Down Expand Up @@ -273,23 +288,6 @@ def update_from(self, other):
self._linespacing = other._linespacing
self.stale = True

def _get_text_metrics_with_cache(
self, renderer, text, fontproperties, ismath):
"""
Call ``renderer.get_text_width_height_descent``, caching the results.
"""
cache_key = (
weakref.ref(renderer),
text,
hash(fontproperties),
ismath,
self.figure.dpi,
)
if cache_key not in self._cached:
self._cached[cache_key] = renderer.get_text_width_height_descent(
text, fontproperties, ismath)
return self._cached[cache_key]

def _get_layout(self, renderer):
"""
Return the extent (bbox) of the text together with
Expand All @@ -305,16 +303,17 @@ def _get_layout(self, renderer):
ys = []

# Full vertical extent of font, including ascenders and descenders:
_, lp_h, lp_d = self._get_text_metrics_with_cache(
_, lp_h, lp_d = _get_text_metrics_with_cache(
renderer, "lp", self._fontproperties,
ismath="TeX" if self.get_usetex() else False)
ismath="TeX" if self.get_usetex() else False, dpi=self.figure.dpi)
min_dy = (lp_h - lp_d) * self._linespacing

for i, line in enumerate(lines):
clean_line, ismath = self._preprocess_math(line)
if clean_line:
w, h, d = self._get_text_metrics_with_cache(
renderer, clean_line, self._fontproperties, ismath)
w, h, d = _get_text_metrics_with_cache(
renderer, clean_line, self._fontproperties,
ismath=ismath, dpi=self.figure.dpi)
else:
w = h = d = 0

Expand Down