Merge pull request #7557 from RaphaelVRossi/check-image-has-fp-when-close

If absent, do not try to close fp when closing image
This commit is contained in:
Andrew Murray 2023-11-24 15:06:39 +11:00 committed by GitHub
commit f8d061c88e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 10 deletions

View File

@ -1,4 +1,5 @@
import io
import logging
import os
import shutil
import sys
@ -1014,6 +1015,15 @@ class TestImage:
except OSError as e:
assert str(e) == "buffer overrun when reading image file"
def test_close_graceful(self, caplog):
with Image.open("Tests/images/hopper.jpg") as im:
copy = im.copy()
with caplog.at_level(logging.DEBUG):
im.close()
copy.close()
assert len(caplog.records) == 0
assert im.fp is None
class MockEncoder:
pass

View File

@ -549,16 +549,17 @@ class Image:
:py:meth:`~PIL.Image.Image.load` method. See :ref:`file-handling` for
more information.
"""
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.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)
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.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)
if getattr(self, "map", None):
self.map = None