From b1cc7df7ba03d32ed340da7270a0e398e0b0a337 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Wed, 6 Mar 2019 21:55:32 +1100 Subject: [PATCH] Only close exclusive fp on Image __exit__ --- Tests/test_image_load.py | 7 +++++++ src/PIL/Image.py | 14 +++++++------- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Tests/test_image_load.py b/Tests/test_image_load.py index d8f323eb8..9937218cd 100644 --- a/Tests/test_image_load.py +++ b/Tests/test_image_load.py @@ -28,3 +28,10 @@ class TestImageLoad(PillowTestCase): os.fstat(fn) self.assertRaises(OSError, os.fstat, fn) + + def test_contextmanager_non_exclusive_fp(self): + with open("Tests/images/hopper.gif", "rb") as fp: + with Image.open(fp): + pass + + self.assertFalse(fp.closed) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 4e1cff312..30f0c2aac 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -578,7 +578,12 @@ class Image(object): return self def __exit__(self, *args): - self.close() + if hasattr(self, "_close__fp"): + self._close__fp() + if (hasattr(self, 'fp') and hasattr(self, '_exclusive_fp') + and self.fp and self._exclusive_fp): + self.fp.close() + self.fp = None def close(self): """ @@ -610,12 +615,7 @@ class Image(object): if sys.version_info.major >= 3: def __del__(self): - if hasattr(self, "_close__fp"): - self._close__fp() - if (hasattr(self, 'fp') and hasattr(self, '_exclusive_fp') - and self.fp and self._exclusive_fp): - self.fp.close() - self.fp = None + self.__exit__() def _copy(self): self.load()