Skip to content

Commit

Permalink
Merge pull request #1914 from zauberzeug/refreshable-return
Browse files Browse the repository at this point in the history
Support return values of refreshable function
  • Loading branch information
rodja authored Oct 29, 2023
2 parents ed3f59f + d249217 commit 6dba0b4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
15 changes: 7 additions & 8 deletions nicegui/functions/refreshable.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,26 +24,25 @@ class RefreshableTarget:
locals: List[Any] = field(default_factory=list)
next_index: int = 0

def run(self, func: Callable[..., Any]) -> Union[None, Awaitable]:
def run(self, func: Callable[..., Any]) -> Union[Any, Awaitable]:
"""Run the function and return the result."""
RefreshableTarget.current_target = self
self.next_index = 0
# pylint: disable=no-else-return
if is_coroutine_function(func):
async def wait_for_result() -> None:
async def wait_for_result() -> Any:
with self.container:
if self.instance is None:
await func(*self.args, **self.kwargs)
return await func(*self.args, **self.kwargs)
else:
await func(self.instance, *self.args, **self.kwargs)
return await func(self.instance, *self.args, **self.kwargs)
return wait_for_result()
else:
with self.container:
if self.instance is None:
func(*self.args, **self.kwargs)
return func(*self.args, **self.kwargs)
else:
func(self.instance, *self.args, **self.kwargs)
return None # required by mypy
return func(self.instance, *self.args, **self.kwargs)


class RefreshableContainer(Element, component='refreshable.js'):
Expand Down Expand Up @@ -75,7 +74,7 @@ def refresh(*args: Any, _instance=self.instance, **kwargs: Any) -> None:
return refresh
return attribute

def __call__(self, *args: Any, **kwargs: Any) -> Union[None, Awaitable]:
def __call__(self, *args: Any, **kwargs: Any) -> Union[Any, Awaitable]:
self.prune()
target = RefreshableTarget(container=RefreshableContainer(), refreshable=self, instance=self.instance,
args=args, kwargs=kwargs)
Expand Down
13 changes: 13 additions & 0 deletions tests/test_refreshable.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,16 @@ def counter(title: str):
screen.wait(0.5)
screen.should_contain('A: 1')
screen.should_contain('B: 1')


def test_refreshable_with_return_value(screen: Screen):
@ui.refreshable
def number_ui() -> int:
ui.label('42')
return 42

answer = number_ui()
assert answer == 42

screen.open('/')
screen.should_contain('42')

0 comments on commit 6dba0b4

Please sign in to comment.