Moved _close_fp into ImageFile

This commit is contained in:
Andrew Murray 2025-01-18 21:22:44 +11:00
parent 4ff18e03b8
commit c78d23d547
2 changed files with 12 additions and 10 deletions

View File

@ -603,16 +603,10 @@ class Image:
def __enter__(self): def __enter__(self):
return self return self
def _close_fp(self):
if getattr(self, "_fp", False):
if self._fp != self.fp:
self._fp.close()
self._fp = DeferredError(ValueError("Operation on closed image"))
if self.fp:
self.fp.close()
def __exit__(self, *args): def __exit__(self, *args):
if hasattr(self, "fp"): from . import ImageFile
if isinstance(self, ImageFile.ImageFile):
if getattr(self, "_exclusive_fp", False): if getattr(self, "_exclusive_fp", False):
self._close_fp() self._close_fp()
self.fp = None self.fp = None

View File

@ -39,7 +39,7 @@ from typing import IO, TYPE_CHECKING, Any, NamedTuple, cast
from . import ExifTags, Image from . import ExifTags, Image
from ._deprecate import deprecate from ._deprecate import deprecate
from ._util import is_path from ._util import DeferredError, is_path
if TYPE_CHECKING: if TYPE_CHECKING:
from ._typing import StrOrBytesPath from ._typing import StrOrBytesPath
@ -166,6 +166,14 @@ class ImageFile(Image.Image):
def _open(self) -> None: def _open(self) -> None:
pass pass
def _close_fp(self):
if getattr(self, "_fp", False):
if self._fp != self.fp:
self._fp.close()
self._fp = DeferredError(ValueError("Operation on closed image"))
if self.fp:
self.fp.close()
def close(self) -> None: def close(self) -> None:
""" """
Closes the file pointer, if possible. Closes the file pointer, if possible.