Skip to content

Commit

Permalink
Implement more functions
Browse files Browse the repository at this point in the history
  • Loading branch information
philippjfr committed Jul 28, 2023
1 parent a413e3f commit cb80216
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
42 changes: 41 additions & 1 deletion param/reactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@
import math
import operator

from collections.abc import Iterable, Iterator
from types import FunctionType, MethodType
from typing import Any, Callable, Optional

Expand Down Expand Up @@ -589,12 +590,51 @@ def __rxor__(self, other):
def __getitem__(self, other):
return self._apply_operator(operator.getitem, other)

def bool_(self):
"""
__bool__ cannot be implemented so it is provided as a method.
"""
return self._apply_operator(bool)

def len(self):
"""
__len__ cannot be implemented so we alternative helper.
__len__ cannot be implemented so it is provided as a method.
"""
return self._apply_operator(len)

def is_(self, other):
"""
Replacement for the ``is`` statement.
"""
return self._apply_operator(operator.is_, other)

def __iter__(self):
if isinstance(self._current, Iterator):
while True:
try:
new = self._apply_operator(next)
new.eval()
except RuntimeError:
break
yield new
return
elif not isinstance(self._current, Iterable):
raise TypeError('cannot unpack non-iterable {type(self._current).__name__} object.')
iterator = []
def iterate(value):
if iterator:
iterate = iterator[0]
else:
iterate = iter(value)
iterator.append(iterate)
try:
yield next(iterate)
except StopIteration as e:
iterator.clear()
raise e
for item in self._apply_operator(iterate):
yield item

def pipe(self, func, *args, **kwargs):
"""
Apply chainable functions.
Expand Down
30 changes: 30 additions & 0 deletions tests/testreactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,33 @@ def test_reactive_dataframe_param_value_method_chain(dataframe):
pd.testing.assert_frame_equal(dfi.eval(), dataframe.groupby('str')[['float']].mean().reset_index())
P.string = 'int'
pd.testing.assert_frame_equal(dfi.eval(), dataframe.groupby('int')[['float']].mean().reset_index())

def test_reactive_len():
i = reactive([1, 2, 3])
l = i.len()
assert l.eval() == 3
i.set([1, 2])
assert l == 2

def test_reactive_bool():
i = reactive(1)
b = i.bool_()
assert b.eval() is True
i.set(0)
assert b.eval() is False

def test_reactive_iter():
i = reactive(('a', 'b'))
a, b = i
assert a.eval() == 'a'
assert b.eval() == 'b'
i.set(('b', 'a'))
assert a.eval() == 'b'
assert b.eval() == 'a'

def test_reactive_is():
i = reactive(None)
is_ = i.is_(None)
assert is_.eval()
i.set(False)
assert not is_.eval()

0 comments on commit cb80216

Please sign in to comment.