Repository navigation
Make IO and RawIO classes usable as context managers - #1975
ptlnextdoor wants to merge 2 commits into
Conversation
|
Hey @ptlnextdoor thanks for the contribution. I think this type of PR will likely have to be discussed at our next maintenance meeting as we haven't discussed this in a quite a while (as you can see from the age of the issue linked). We will provide feedback once we decide if we would want to go forward with this possibility. |
Add __enter__, __exit__ and a default no-op close() to BaseIO and BaseRawIO, so that 'with SomeIO(...) as io:' calls close() on exit. Fixes NeuralEnsemble#175
BaseRawWithBufferApiIO.close() now closes the memmap and HDF5 buffers, so leaving a with block frees them. __del__ calls close().
277d07d to
af5980d
Compare
| def __exit__(self, exc_type, exc_value, traceback): | ||
| self.close() | ||
|
|
||
| def close(self): |
There was a problem hiding this comment.
why are you making this public?
There was a problem hiding this comment.
__exit__ has to call something, and the issue asks for with SomeIO(...) as io: to close the file. close is also the name existing IOs already use publicly (NixIO, NWBIO, MedIO, ElphyIO, BrainwareSrcIO), so the base class now declares it as a no-op that those classes override. The only other change is that BaseRawWithBufferApiIO.__del__ now calls the new public close(). If you prefer a private hook such as _close, say so and I will change it.
|
About the failing |
Part of #175
What was broken
IO classes could not be used in a
withstatement. OnlyNixIO,NixIOFrandEDFRawIOhad__enter__and__exit__.What changed
BaseIOandBaseRawIOget__enter__,__exit__and a defaultclose().__exit__callsclose().BaseRawWithBufferApiIO.close()now closes the memmap and HDF5 buffers.__del__calls it, so the cleanup is the same as before and can also run at the end of awithblock. Callingclose()twice is safe.close()keep it. Readers that free handles only in their own__del__(for exampleBlackrockRawIOandAlphaOmegaRawIO) are not changed, sowithdoes not release their handles yet.open()method and lazy opening, which the issue also discusses, are out of scope.How it was tested
neo/test/iotest/test_context_manager.py. Thewithtests fail onmaster(does not support the context manager protocol) and pass now. They check thatclose()runs on normal exit and on an exception, and that a buffer-API reader closes its files once, even after a secondclose().black -l 120is clean. I ran the new test andtest_examplerawio.py. The ExampleIO tests need the ephy_testing_data files, which are not available here.AI disclosure: this PR was prepared with AI assistance (Claude, Anthropic).