Skip to content
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

Use functools.lru_cache for hopper() #7912

Merged
merged 7 commits into from
Apr 1, 2024
Merged
Changes from 1 commit
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
31 changes: 17 additions & 14 deletions Tests/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import sys
import sysconfig
import tempfile
from functools import lru_cache
from io import BytesIO
from typing import Any, Callable, Sequence

Expand Down Expand Up @@ -250,25 +251,27 @@ def tostring(im: Image.Image, string_format: str, **options: Any) -> bytes:
return out.getvalue()


def hopper(mode: str | None = None, cache: dict[str, Image.Image] = {}) -> Image.Image:
def hopper(mode: str | None = None) -> Image.Image:
# Use caching to reduce reading from disk but so an original copy is
# returned each time and the cached image isn't modified by tests
# (for fast, isolated, repeatable tests).
hugovk marked this conversation as resolved.
Show resolved Hide resolved
return _cached_hopper(mode).copy()


@lru_cache(maxsize=None)
def _cached_hopper(mode: str | None = None) -> Image.Image:
if mode is None:
# Always return fresh not-yet-loaded version of image.
# Operations on not-yet-loaded images is separate class of errors
hugovk marked this conversation as resolved.
Show resolved Hide resolved
# what we should catch.
hugovk marked this conversation as resolved.
Show resolved Hide resolved
return Image.open("Tests/images/hopper.ppm")
hugovk marked this conversation as resolved.
Show resolved Hide resolved
# Use caching to reduce reading from disk but so an original copy is
# returned each time and the cached image isn't modified by tests
# (for fast, isolated, repeatable tests).
im = cache.get(mode)
if im is None:
if mode == "F":
im = hopper("L").convert(mode)
elif mode[:4] == "I;16":
im = hopper("I").convert(mode)
else:
im = hopper().convert(mode)
cache[mode] = im
return im.copy()
if mode == "F":
im = _cached_hopper("L").convert(mode)
elif mode[:4] == "I;16":
im = _cached_hopper("I").convert(mode)
else:
im = _cached_hopper().convert(mode)
return im


def djpeg_available() -> bool:
Expand Down
Loading