Skip to content

Commit 277d07d

Browse files
committed
Make IO and RawIO classes usable as context managers
Add __enter__, __exit__ and a default no-op close() to BaseIO and BaseRawIO, so that 'with SomeIO(...) as io:' calls close() on exit. Fixes #175
1 parent e899f3e commit 277d07d

3 files changed

Lines changed: 64 additions & 0 deletions

File tree

‎neo/io/baseio.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ def __init__(self, filename: str | Path = None, **kargs):
118118
if not corelogger.handlers and not rootlogger.handlers:
119119
corelogger.addHandler(logging_handler)
120120

121+
def __enter__(self):
122+
return self
123+
124+
def __exit__(self, exc_type, exc_value, traceback):
125+
self.close()
126+
127+
def close(self):
128+
"""
129+
Release resources such as open file handles.
130+
IO classes that hold resources override this method.
131+
"""
132+
121133
######## General read/write methods #######################
122134
def read(self, lazy: bool = False, **kargs):
123135
"""

‎neo/rawio/baserawio.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,18 @@ def __init__(self, use_cache: bool = False, cache_path: str = "same_as_resource"
186186

187187
self._has_buffer_description_api = False
188188

189+
def __enter__(self):
190+
return self
191+
192+
def __exit__(self, exc_type, exc_value, traceback):
193+
self.close()
194+
195+
def close(self):
196+
"""
197+
Release resources such as open file handles.
198+
IO classes that hold resources override this method.
199+
"""
200+
189201
def has_buffer_description_api(self) -> bool:
190202
"""
191203
Return if the reader handle the buffer API.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Tests that IO and RawIO classes can be used as context managers
3+
"""
4+
5+
import unittest
6+
7+
from neo.io.exampleio import ExampleIO
8+
from neo.rawio.examplerawio import ExampleRawIO
9+
10+
11+
class TestContextManager(unittest.TestCase):
12+
def _check(self, cls):
13+
closed = []
14+
15+
class Tracked(cls):
16+
def close(self):
17+
closed.append(True)
18+
19+
with Tracked(filename="fake.fake") as io:
20+
self.assertIsInstance(io, Tracked)
21+
self.assertEqual(closed, [True])
22+
23+
with self.assertRaises(ValueError), Tracked(filename="fake.fake"):
24+
raise ValueError
25+
self.assertEqual(closed, [True, True])
26+
27+
def test_io(self):
28+
self._check(ExampleIO)
29+
30+
def test_rawio(self):
31+
self._check(ExampleRawIO)
32+
33+
def test_default_close_is_noop(self):
34+
with ExampleIO(filename="fake.fake") as io:
35+
pass
36+
io.close()
37+
38+
39+
if __name__ == "__main__":
40+
unittest.main()

0 commit comments

Comments
 (0)