@@ -66,24 +66,24 @@ def _get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):
66
66
"""Call ``renderer.get_text_width_height_descent``, caching the results."""
67
67
# Cached based on a copy of fontprop so that later in-place mutations of
68
68
# the passed-in argument do not mess up the cache.
69
- func = _get_text_metrics_function (weakref . ref ( renderer ) )
69
+ func = _get_text_metrics_function (renderer )
70
70
return func (text , fontprop .copy (), ismath , dpi )
71
71
72
72
73
- @ functools . lru_cache ( 25 )
74
- def _get_text_metrics_function (renderer_ref ):
75
-
76
- @ functools . lru_cache ( 4096 )
77
- def _text_metrics ( text , fontprop , ismath , dpi ):
78
- # dpi is unused, but participates in cache invalidation (via the renderer).
79
- renderer = renderer_ref ()
80
- if renderer is None :
81
- raise RuntimeError (
82
- "You are trying to get the font metrics for a renderer that no "
83
- "longer exists. There is likely a deeper bug someplace else "
84
- "as this should never happen."
85
- )
86
- return renderer . get_text_width_height_descent ( text , fontprop , ismath )
73
+ # use mutable default to carry hidden global state
74
+ def _get_text_metrics_function (inp_renderer , _cache = weakref . WeakKeyDictionary () ):
75
+ if ( _text_metrics := _cache . get ( inp_renderer , None )) is None :
76
+ renderer_ref = weakref . ref ( inp_renderer )
77
+ @ functools . lru_cache ( 4096 )
78
+ def _text_metrics ( text , fontprop , ismath , dpi ):
79
+ # dpi is unused, but participates in cache invalidation (via the renderer).
80
+ if ( lcl_renderer := renderer_ref ()) is None :
81
+ raise RuntimeError (
82
+ "Trying to get text metrics for a renderer that no longer exists. "
83
+ "This should never happen and is evidence of a bug elsewhere. "
84
+ )
85
+ return lcl_renderer . get_text_width_height_descent ( text , fontprop , ismath )
86
+ _cache [ inp_renderer ] = _text_metrics
87
87
88
88
return _text_metrics
89
89
0 commit comments