Skip to content

Commit 504a2e1

Browse files
committed
Use functools.lru_cache for hopper()
1 parent e3aeaa6 commit 504a2e1

1 file changed

Lines changed: 17 additions & 14 deletions

File tree

Tests/helper.py

Lines changed: 17 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,25 +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 so an original copy is
256+
# returned each time and the cached image isn't modified by tests
257+
# (for fast, isolated, repeatable tests).
258+
return _cached_hopper(mode).copy()
259+
260+
261+
@lru_cache(maxsize=None)
262+
def _cached_hopper(mode: str | None = None) -> Image.Image:
254263
if mode is None:
255264
# Always return fresh not-yet-loaded version of image.
256265
# Operations on not-yet-loaded images is separate class of errors
257266
# what we should catch.
258267
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-
elif mode[:4] == "I;16":
267-
im = hopper("I").convert(mode)
268-
else:
269-
im = hopper().convert(mode)
270-
cache[mode] = im
271-
return im.copy()
268+
if mode == "F":
269+
im = _cached_hopper("L").convert(mode)
270+
elif mode[:4] == "I;16":
271+
im = _cached_hopper("I").convert(mode)
272+
else:
273+
im = _cached_hopper().convert(mode)
274+
return im
272275

273276

274277
def djpeg_available() -> bool:

0 commit comments

Comments
 (0)