diff --git a/neo/io/baseio.py b/neo/io/baseio.py index 7b995d62d..c93cb3ff4 100644 --- a/neo/io/baseio.py +++ b/neo/io/baseio.py @@ -118,6 +118,18 @@ def __init__(self, filename: str | Path = None, **kargs): if not corelogger.handlers and not rootlogger.handlers: corelogger.addHandler(logging_handler) + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + """ + Release resources such as open file handles. + IO classes that hold resources override this method. + """ + ######## General read/write methods ####################### def read(self, lazy: bool = False, **kargs): """ diff --git a/neo/rawio/baserawio.py b/neo/rawio/baserawio.py index b694197ec..808a06609 100644 --- a/neo/rawio/baserawio.py +++ b/neo/rawio/baserawio.py @@ -186,6 +186,18 @@ def __init__(self, use_cache: bool = False, cache_path: str = "same_as_resource" self._has_buffer_description_api = False + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + def close(self): + """ + Release resources such as open file handles. + IO classes that hold resources override this method. + """ + def has_buffer_description_api(self) -> bool: """ Return if the reader handle the buffer API. diff --git a/neo/test/iotest/test_context_manager.py b/neo/test/iotest/test_context_manager.py new file mode 100644 index 000000000..f9af28922 --- /dev/null +++ b/neo/test/iotest/test_context_manager.py @@ -0,0 +1,40 @@ +""" +Tests that IO and RawIO classes can be used as context managers +""" + +import unittest + +from neo.io.exampleio import ExampleIO +from neo.rawio.examplerawio import ExampleRawIO + + +class TestContextManager(unittest.TestCase): + def _check(self, cls): + closed = [] + + class Tracked(cls): + def close(self): + closed.append(True) + + with Tracked(filename="fake.fake") as io: + self.assertIsInstance(io, Tracked) + self.assertEqual(closed, [True]) + + with self.assertRaises(ValueError), Tracked(filename="fake.fake"): + raise ValueError + self.assertEqual(closed, [True, True]) + + def test_io(self): + self._check(ExampleIO) + + def test_rawio(self): + self._check(ExampleRawIO) + + def test_default_close_is_noop(self): + with ExampleIO(filename="fake.fake") as io: + pass + io.close() + + +if __name__ == "__main__": + unittest.main()