Skip to content

Commit

Permalink
fix: close handles on object deletion (#116)
Browse files Browse the repository at this point in the history
* fix: close on del

* fix: add warning
  • Loading branch information
tlambert03 committed Dec 8, 2022
1 parent 9b36476 commit bbd914b
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/nd2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"BinaryLayers",
"imread",
"is_supported_file",
"is_legacy",
"ND2File",
"read_chunkmap",
"rescue_nd2",
Expand All @@ -20,5 +21,5 @@
from . import structures
from ._binary import BinaryLayer, BinaryLayers
from ._chunkmap import read_chunkmap, rescue_nd2
from ._util import AXIS, is_supported_file
from ._util import AXIS, is_legacy, is_supported_file
from .nd2file import ND2File, imread
17 changes: 17 additions & 0 deletions src/nd2/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,23 @@ def is_supported_file(
return fh.read(4) in (NEW_HEADER_MAGIC, OLD_HEADER_MAGIC)


def is_legacy(path: "StrOrBytesPath") -> bool:
"""Return `True` if `path` is a legacy ND2 file.
Parameters
----------
path : Union[str, bytes, PathLike]
A path to query
Returns
-------
bool
Whether the file is a legacy ND2 file.
"""
with open(path, "rb") as fh:
return fh.read(4) == OLD_HEADER_MAGIC


def get_reader(
path: str,
validate_frames: bool = False,
Expand Down
10 changes: 10 additions & 0 deletions src/nd2/nd2file.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,16 @@ def __enter__(self) -> ND2File:
self.open()
return self

def __del__(self) -> None:
"""Delete file handle on garbage collection."""
if not getattr(self, "_closed", True):
warnings.warn(
"ND2File file not closed before garbage collection. "
"Please use `with ND2File(...):` context or call `.close()`.",
stacklevel=2,
)
self._rdr.close()

def __exit__(self, *_) -> None:
self.close()

Expand Down
12 changes: 12 additions & 0 deletions tests/test_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,15 @@ def test_recorded_data() -> None:
-4155.462732842248,
3916.7250000000004,
]


def test_gc_triggers_cleanup(single_nd2):
# this test takes advantage of the `no_files_left_open``
# fixture in conftest to ensure that the file is closed
import gc

f: ND2File | None = ND2File(single_nd2)

with pytest.warns(UserWarning, match="ND2File file not closed"):
f = None # noqa: F841
gc.collect()

0 comments on commit bbd914b

Please sign in to comment.