From 14af7bb5ac022bd4b19fb7f716a59bf5bea0c1bb Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 29 Jul 2020 08:13:56 +1000 Subject: [PATCH] Do not try to close fp if fp is empty --- Tests/test_image_load.py | 9 +++++++++ src/PIL/Image.py | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Tests/test_image_load.py b/Tests/test_image_load.py index 7dd3b294f..f7fe99bb4 100644 --- a/Tests/test_image_load.py +++ b/Tests/test_image_load.py @@ -1,3 +1,4 @@ +import logging import os import pytest @@ -23,6 +24,14 @@ def test_close(): im.getpixel((0, 0)) +def test_close_after_load(caplog): + im = Image.open("Tests/images/hopper.gif") + im.load() + with caplog.at_level(logging.DEBUG): + im.close() + assert len(caplog.records) == 0 + + def test_contextmanager(): fn = None with Image.open("Tests/images/hopper.gif") as im: diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 8ab67d55e..00adf2d0a 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -594,7 +594,8 @@ class Image: try: if hasattr(self, "_close__fp"): self._close__fp() - self.fp.close() + if self.fp: + self.fp.close() self.fp = None except Exception as msg: logger.debug("Error closing: %s", msg)