Skip to content

Commit 2237677

Browse files
authored
Merge pull request #7912 from hugovk/hopper-lru-cache
2 parents da13358 + 512ee3f commit 2237677

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

Tests/helper.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import sys
1212
import sysconfig
1313
import tempfile
14+
from functools import lru_cache
1415
from io import BytesIO
1516
from typing import Any, Callable, Sequence
1617

@@ -250,23 +251,27 @@ def tostring(im: Image.Image, string_format: str, **options: Any) -> bytes:
250251
return out.getvalue()
251252

252253

253-
def hopper(mode: str | None = None, cache: dict[str, Image.Image] = {}) -> Image.Image:
254+
def hopper(mode: str | None = None) -> Image.Image:
255+
# Use caching to reduce reading from disk, but return a copy
256+
# so that the cached image isn't modified by the tests
257+
# (for fast, isolated, repeatable tests).
258+
254259
if mode is None:
255260
# Always return fresh not-yet-loaded version of image.
256-
# Operations on not-yet-loaded images is separate class of errors
257-
# what we should catch.
261+
# Operations on not-yet-loaded images are a separate class of errors
262+
# that we should catch.
258263
return Image.open("Tests/images/hopper.ppm")
259-
# Use caching to reduce reading from disk but so an original copy is
260-
# returned each time and the cached image isn't modified by tests
261-
# (for fast, isolated, repeatable tests).
262-
im = cache.get(mode)
263-
if im is None:
264-
if mode == "F":
265-
im = hopper("L").convert(mode)
266-
else:
267-
im = hopper().convert(mode)
268-
cache[mode] = im
269-
return im.copy()
264+
265+
return _cached_hopper(mode).copy()
266+
267+
268+
@lru_cache
269+
def _cached_hopper(mode: str) -> Image.Image:
270+
if mode == "F":
271+
im = hopper("L")
272+
else:
273+
im = hopper()
274+
return im.convert(mode)
270275

271276

272277
def djpeg_available() -> bool:

0 commit comments

Comments
 (0)