Skip to content

Commit

Permalink
Merge pull request #3683 from radarhere/exclusive
Browse files Browse the repository at this point in the history
Only close original fp in __del__ and __exit__ if original fp is exclusive
  • Loading branch information
hugovk committed Mar 18, 2019
2 parents c8fa5be + 9bdab56 commit b8ea881
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
12 changes: 12 additions & 0 deletions Tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,18 @@ def test_no_resource_warning_on_save(self):
with Image.open(test_file) as im:
self.assert_warning(None, im.save, temp_file)

def test_load_on_nonexclusive_multiframe(self):
with open("Tests/images/frozenpond.mpo", "rb") as fp:
def act(fp):
im = Image.open(fp)
im.load()
act(fp)

with Image.open(fp) as im:
im.load()

self.assertFalse(fp.closed)


class MockEncoder(object):
pass
Expand Down
10 changes: 5 additions & 5 deletions src/PIL/Image.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,11 +578,11 @@ def __enter__(self):
return self

def __exit__(self, *args):
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()
if hasattr(self, 'fp') and getattr(self, '_exclusive_fp', False):
if hasattr(self, "_close__fp"):
self._close__fp()
if self.fp:
self.fp.close()
self.fp = None

def close(self):
Expand Down
7 changes: 2 additions & 5 deletions src/PIL/WebPImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def _save_all(im, fp, filename):
# will preserve non-alpha modes
total = 0
for ims in [im]+append_images:
total += 1 if not hasattr(ims, "n_frames") else ims.n_frames
total += getattr(ims, "n_frames", 1)
if total == 1:
_save(im, fp, filename)
return
Expand Down Expand Up @@ -254,10 +254,7 @@ def _save_all(im, fp, filename):
try:
for ims in [im]+append_images:
# Get # of frames in this image
if not hasattr(ims, "n_frames"):
nfr = 1
else:
nfr = ims.n_frames
nfr = getattr(ims, "n_frames", 1)

for idx in range(nfr):
ims.seek(idx)
Expand Down

0 comments on commit b8ea881

Please sign in to comment.