Skip to content

Commit f8d061c

Browse files
authored
Merge pull request #7557 from RaphaelVRossi/check-image-has-fp-when-close
If absent, do not try to close fp when closing image
2 parents 9694cfc + 8186c63 commit f8d061c

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

Tests/test_image.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import io
2+
import logging
23
import os
34
import shutil
45
import sys
@@ -1014,6 +1015,15 @@ def test_fli_overrun2(self):
10141015
except OSError as e:
10151016
assert str(e) == "buffer overrun when reading image file"
10161017

1018+
def test_close_graceful(self, caplog):
1019+
with Image.open("Tests/images/hopper.jpg") as im:
1020+
copy = im.copy()
1021+
with caplog.at_level(logging.DEBUG):
1022+
im.close()
1023+
copy.close()
1024+
assert len(caplog.records) == 0
1025+
assert im.fp is None
1026+
10171027

10181028
class MockEncoder:
10191029
pass

src/PIL/Image.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -549,16 +549,17 @@ def close(self):
549549
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
550550
more information.
551551
"""
552-
try:
553-
if getattr(self, "_fp", False):
554-
if self._fp != self.fp:
555-
self._fp.close()
556-
self._fp = DeferredError(ValueError("Operation on closed image"))
557-
if self.fp:
558-
self.fp.close()
559-
self.fp = None
560-
except Exception as msg:
561-
logger.debug("Error closing: %s", msg)
552+
if hasattr(self, "fp"):
553+
try:
554+
if getattr(self, "_fp", False):
555+
if self._fp != self.fp:
556+
self._fp.close()
557+
self._fp = DeferredError(ValueError("Operation on closed image"))
558+
if self.fp:
559+
self.fp.close()
560+
self.fp = None
561+
except Exception as msg:
562+
logger.debug("Error closing: %s", msg)
562563

563564
if getattr(self, "map", None):
564565
self.map = None

0 commit comments

Comments
 (0)