Moved code closing fp and _fp into common method

This commit is contained in:
Andrew Murray 2023-11-29 20:05:17 +11:00
parent 5431b15bd2
commit 5fb86c55ed

View File

@ -527,15 +527,18 @@ class Image:
def __enter__(self): def __enter__(self):
return self return self
def _close_fp(self):
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()
def __exit__(self, *args): def __exit__(self, *args):
if hasattr(self, "fp"): if hasattr(self, "fp"):
if getattr(self, "_exclusive_fp", False): if getattr(self, "_exclusive_fp", False):
if getattr(self, "_fp", False): self._close_fp()
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 self.fp = None
def close(self): def close(self):
@ -552,12 +555,7 @@ class Image:
""" """
if hasattr(self, "fp"): if hasattr(self, "fp"):
try: try:
if getattr(self, "_fp", False): self._close_fp()
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 self.fp = None
except Exception as msg: except Exception as msg:
logger.debug("Error closing: %s", msg) logger.debug("Error closing: %s", msg)