Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions neo/io/baseio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
12 changes: 12 additions & 0 deletions neo/rawio/baserawio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
40 changes: 40 additions & 0 deletions neo/test/iotest/test_context_manager.py
Original file line number Diff line number Diff line change
@@ -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()