Only close exclusive fp on Image __exit__

This commit is contained in:
Andrew Murray 2019-03-06 21:55:32 +11:00
parent 8194677516
commit b1cc7df7ba
2 changed files with 14 additions and 7 deletions

View File

@ -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)

View File

@ -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()