Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: close handles on object deletion #116

Merged
merged 2 commits into from
Dec 8, 2022
Merged
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
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()