Skip to content

Commit d71cf16

Browse files
authored
Merge pull request #7566 from radarhere/exit
2 parents 119885a + 5fb86c5 commit d71cf16

2 files changed

Lines changed: 18 additions & 14 deletions

File tree

Tests/test_image.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,6 +1016,11 @@ def test_fli_overrun2(self):
10161016
except OSError as e:
10171017
assert str(e) == "buffer overrun when reading image file"
10181018

1019+
def test_exit_fp(self):
1020+
with Image.new("L", (1, 1)) as im:
1021+
pass
1022+
assert not hasattr(im, "fp")
1023+
10191024
def test_close_graceful(self, caplog):
10201025
with Image.open("Tests/images/hopper.jpg") as im:
10211026
copy = im.copy()

src/PIL/Image.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -530,15 +530,19 @@ def _new(self, im):
530530
def __enter__(self):
531531
return self
532532

533+
def _close_fp(self):
534+
if getattr(self, "_fp", False):
535+
if self._fp != self.fp:
536+
self._fp.close()
537+
self._fp = DeferredError(ValueError("Operation on closed image"))
538+
if self.fp:
539+
self.fp.close()
540+
533541
def __exit__(self, *args):
534-
if hasattr(self, "fp") and getattr(self, "_exclusive_fp", False):
535-
if getattr(self, "_fp", False):
536-
if self._fp != self.fp:
537-
self._fp.close()
538-
self._fp = DeferredError(ValueError("Operation on closed image"))
539-
if self.fp:
540-
self.fp.close()
541-
self.fp = None
542+
if hasattr(self, "fp"):
543+
if getattr(self, "_exclusive_fp", False):
544+
self._close_fp()
545+
self.fp = None
542546

543547
def close(self):
544548
"""
@@ -554,12 +558,7 @@ def close(self):
554558
"""
555559
if hasattr(self, "fp"):
556560
try:
557-
if getattr(self, "_fp", False):
558-
if self._fp != self.fp:
559-
self._fp.close()
560-
self._fp = DeferredError(ValueError("Operation on closed image"))
561-
if self.fp:
562-
self.fp.close()
561+
self._close_fp()
563562
self.fp = None
564563
except Exception as msg:
565564
logger.debug("Error closing: %s", msg)

0 commit comments

Comments
 (0)