From 2cc6bd244d89198eed0d46fc1563a19df41563ef Mon Sep 17 00:00:00 2001 From: Vitaliy Mysak Date: Wed, 7 Aug 2024 11:03:03 -0700 Subject: [PATCH] Add __del__ handling to SubTextIO --- src/multicsv/subtextio.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/multicsv/subtextio.py b/src/multicsv/subtextio.py index 76414dd..a8087ed 100644 --- a/src/multicsv/subtextio.py +++ b/src/multicsv/subtextio.py @@ -103,6 +103,14 @@ class allows for convenient and isolated operations within a given """ def __init__(self, base_io: TextIO, start: int, end: int): + self._initialized = False + self._base_io = base_io + self._start = start + self._end = end + self._position = 0 # Position within the SubTextIO + self._closed = base_io.closed + self._buffer = "" + if end < start or start < 0: raise InvalidSubtextCoordinates( f"Invalid range [{start},{end}] passed to SubTextIO.") @@ -116,13 +124,9 @@ def __init__(self, base_io: TextIO, start: int, end: int): raise BaseMustBeReadable("Base io must be readable" " if existing content is to be modified.") - self._base_io = base_io - self._start = start - self._end = end - self._position = 0 # Position within the SubTextIO - self._closed = base_io.closed self._load() self._initial_length = self.buffer_length + self._initialized = True def _load(self) -> None: """ @@ -350,3 +354,10 @@ def __exit__(self, exc_val: Optional[BaseException], exc_tb: Optional[object]) -> None: self.close() + + def __del__(self) -> None: + if self._initialized: + try: + self.close() + except BaseIOClosed: + pass