Skip to content

Commit

Permalink
Merge pull request #7566 from radarhere/exit
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Dec 31, 2023
2 parents 119885a + 5fb86c5 commit d71cf16
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
5 changes: 5 additions & 0 deletions Tests/test_image.py
Expand Up @@ -1016,6 +1016,11 @@ def test_fli_overrun2(self):
except OSError as e:
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):
with Image.open("Tests/images/hopper.jpg") as im:
copy = im.copy()
Expand Down
27 changes: 13 additions & 14 deletions src/PIL/Image.py
Expand Up @@ -530,15 +530,19 @@ def _new(self, im):
def __enter__(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):
if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False):
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()
self.fp = None
if hasattr(self, "fp"):
if getattr(self, "_exclusive_fp", False):
self._close_fp()
self.fp = None

def close(self):
"""
Expand All @@ -554,12 +558,7 @@ def close(self):
"""
if hasattr(self, "fp"):
try:
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()
self._close_fp()
self.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)
Expand Down

0 comments on commit d71cf16

Please sign in to comment.