Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 3 additions & 2 deletions apis/python/src/tiledbsoma/_soma_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,9 @@ def __getitem__(self, key: str) -> CollectionElementType:
clib_type=None if entry.tiledb_type is None else entry.tiledb_type.name,
)

# Since we just opened this object, we own it and should close it.
self._close_stack.enter_context(entry.soma)
if self._is_running_in_context:
# Since we just opened this object, we own it and should close it.
self._close_stack.enter_context(entry.soma)

return cast("CollectionElementType", entry.soma)

Expand Down
5 changes: 4 additions & 1 deletion apis/python/src/tiledbsoma/_soma_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class SOMAObject:
_handle_type: ClassVar[_tdb_handles.RawHandle]
"""Class variable of the clib class handle used to open this object type."""

__slots__ = ("_close_stack", "_context", "_handle", "_metadata", "_timestamp_ms", "_uri")
__slots__ = ("_close_stack", "_context", "_handle", "_is_running_in_context", "_metadata", "_timestamp_ms", "_uri")

soma_type: ClassVar[LiteralString]
"""A string describing the SOMA type of this object. This is constant.
Expand Down Expand Up @@ -154,6 +154,7 @@ def __init__(
if not isinstance(handle, self._handle_type):
raise TypeError("Internal error: Unexpected handle type {type(handle)}. Expected {self._handle_type}.")
self._close_stack = ExitStack()
self._is_running_in_context = False
"""An exit stack to manage closing handles owned by this object.

This is used to manage both our direct handle (in the case of simple
Expand Down Expand Up @@ -234,9 +235,11 @@ def metadata(self) -> MutableMapping[str, Any]:
__hash__ = object.__hash__

def __enter__(self) -> Self:
self._is_running_in_context = True
return self

def __exit__(self, *_: Any) -> None: # noqa: ANN401
self._is_running_in_context = False
self.close()

def __del__(self) -> None:
Expand Down