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

Add SafeCloseable context manager wrapper #5251

Merged
merged 9 commits into from
Mar 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
21 changes: 21 additions & 0 deletions py/server/deephaven/jcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,3 +304,24 @@ def _j_array_to_series(dtype: DType, j_array: jpy.JType, conv_null: bool) -> pd.
s = pd.Series(data=np_array, copy=False)

return s


class SafeCloseable:
"""A context manager wrapper of Java SafeCloseable to emulate Java try-with-resources."""
arman-ddl marked this conversation as resolved.
Show resolved Hide resolved
arman-ddl marked this conversation as resolved.
Show resolved Hide resolved
def __init__(self, j_safe_closeable):
self._j_safe_closeable = j_safe_closeable
self.closed = False
arman-ddl marked this conversation as resolved.
Show resolved Hide resolved

def __enter__(self):
return self

def close(self):
if not self.closed:
self.closed = True
self._j_safe_closeable.close()
chipkent marked this conversation as resolved.
Show resolved Hide resolved

def __exit__(self, exc_type, exc_value, traceback):
self.close()

def __del__(self):
self.close()
9 changes: 8 additions & 1 deletion py/server/tests/test_jcompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
import unittest

from deephaven import dtypes
from deephaven.jcompat import j_function, j_lambda
from deephaven.jcompat import j_function, j_lambda, SafeCloseable
from tests.testbase import BaseTestCase

import jpy

_JSharedContext = jpy.get_type("io.deephaven.engine.table.SharedContext")

class JCompatTestCase(BaseTestCase):
def test_j_function(self):
Expand All @@ -29,6 +30,12 @@ def int_to_str(v: int) -> str:
r = j_func.apply(10)
self.assertEqual(r, "10")

def test_safe_closeable(self):
safe_closeable = SafeCloseable(_JSharedContext.makeSharedContext())
chipkent marked this conversation as resolved.
Show resolved Hide resolved
with safe_closeable:
chipkent marked this conversation as resolved.
Show resolved Hide resolved
pass
arman-ddl marked this conversation as resolved.
Show resolved Hide resolved
self.assertEqual(safe_closeable.closed, True)


if __name__ == "__main__":
unittest.main()
Loading