Skip to content

Commit

Permalink
Do not assign new fp attribute to image when exiting context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed Nov 24, 2023
1 parent 04a4d54 commit 5431b15
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
5 changes: 5 additions & 0 deletions Tests/test_image.py
Expand Up @@ -1015,6 +1015,11 @@ def test_fli_overrun2(self):
except OSError as e:
assert str(e) == "buffer overrun when reading image file"

def test_exit_fp(self):
with Image.new("L", (1, 1)) as im:
pass
assert not hasattr(im, "fp")

def test_close_graceful(self, caplog):
with Image.open("Tests/images/hopper.jpg") as im:
copy = im.copy()
Expand Down
17 changes: 9 additions & 8 deletions src/PIL/Image.py
Expand Up @@ -528,14 +528,15 @@ def __enter__(self):
return self

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

def close(self):
"""
Expand Down

0 comments on commit 5431b15

Please sign in to comment.