Merge pull request #7566 from radarhere/exit

This commit is contained in:
Hugo van Kemenade 2023-12-31 17:37:43 +02:00 committed by GitHub
commit d71cf168ee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 14 deletions

View File

@ -1016,6 +1016,11 @@ class TestImage:
except OSError as e: except OSError as e:
assert str(e) == "buffer overrun when reading image file" assert str(e) == "buffer overrun when reading image file"
def test_exit_fp(self):
with Image.new("L", (1, 1)) as im:
pass
assert not hasattr(im, "fp")
def test_close_graceful(self, caplog): def test_close_graceful(self, caplog):
with Image.open("Tests/images/hopper.jpg") as im: with Image.open("Tests/images/hopper.jpg") as im:
copy = im.copy() copy = im.copy()

View File

@ -530,15 +530,19 @@ 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") and getattr(self, "_exclusive_fp", False): if hasattr(self, "fp"):
if getattr(self, "_fp", False): if getattr(self, "_exclusive_fp", False):
if self._fp != self.fp: self._close_fp()
self._fp.close() self.fp = None
self._fp = DeferredError(ValueError("Operation on closed image"))
if self.fp:
self.fp.close()
self.fp = None
def close(self): def close(self):
""" """
@ -554,12 +558,7 @@ class Image:
""" """
if hasattr(self, "fp"): if hasattr(self, "fp"):
try: try:
if getattr(self, "_fp", False): self._close_fp()
if self._fp != self.fp:
self._fp.close()
self._fp = DeferredError(ValueError("Operation on closed image"))
if self.fp:
self.fp.close()
self.fp = None self.fp = None
except Exception as msg: except Exception as msg:
logger.debug("Error closing: %s", msg) logger.debug("Error closing: %s", msg)