diff --git a/Tests/test_image.py b/Tests/test_image.py index 9efd4c467..0c6843346 100644 --- a/Tests/test_image.py +++ b/Tests/test_image.py @@ -1014,6 +1014,21 @@ class TestImage: except OSError as e: assert str(e) == "buffer overrun when reading image file" + @pytest.fixture(scope="function") + def inject_caplog(self, caplog): + self._caplog = caplog + + @pytest.mark.usefixtures("inject_caplog") + def test_close_graceful(self): + with Image.open("Tests/images/hopper.jpg") as im: + copy = im.copy() + im.close() + copy.close() + + assert len(self._caplog.records) == 0 + assert im.fp is None + assert copy.fp is None + class MockEncoder: pass diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 546d90203..c873a93e7 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -550,12 +550,13 @@ class Image: 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() + if hasattr(self, "fp"): + 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)