Skip to content

Commit

Permalink
Example script for ineterminate progress bar with a long running comp…
Browse files Browse the repository at this point in the history
…utation (pyapp-kit#579)
  • Loading branch information
GenevieveBuckley authored Sep 26, 2023
1 parent 2760ae7 commit e47338a
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/examples/progress_bars/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Progress bars examples
# Progress bar examples

Examples of progress bars in magicgui.
31 changes: 31 additions & 0 deletions docs/examples/progress_bars/progress_indeterminate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""# Indeterminate progress bar
Example of an indeterminate progress bar for a long running computation
of unknown time.
"""
import time

from superqt.utils import thread_worker

from magicgui import magicgui
from magicgui.tqdm import tqdm


@magicgui(call_button=True, layout="horizontal")
def long_running(sleep_time=5):
"""Long running computation with an indeterminate progress bar."""
# Here tqdm is not provided an iterable argument, or the 'total' kwarg
# so it cannot calculate the expected number of iterations
# which means it will create an indeterminate progress bar
with tqdm() as pbar:
# It is best practice to use a separate thread for long running computations
# This makes the function non-blocking, you can still interact with the widget
@thread_worker(connect={"finished": lambda: pbar.progressbar.hide()})
def sleep(secs):
time.sleep(secs)

sleep(sleep_time)


long_running.show(run=True)
24 changes: 24 additions & 0 deletions tests/test_tqdm.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ def test_tqdm_outside_of_functiongui():
assert tuple(trange(5)) == tuple(range(5))


def test_indeterminate_tqdm_outside_of_functiongui():
"""Test that we can have tqdm with an indeterminate total range."""
with tqdm(total=None) as pbar:
assert pbar.total is None
assert pbar.n == 0
pbar.update()
assert pbar.n == 1


def test_disabled_tqdm():
"""Test that a disabled tqdm does not have a progressbar or magicgui."""

Expand Down Expand Up @@ -137,6 +146,21 @@ def long_func(steps=2):
assert len(long_func._tqdm_pbars) == 1


def test_indeterminate_tqdm_inside_magicgui():
"""Test that we can have tqdm with an indeterminate total range."""

@magicgui
def long_func():
"""Long running computation with indeterminate range."""
with tqdm(total=None):
pass

long_func.show()
assert not long_func._tqdm_pbars
long_func()
assert len(long_func._tqdm_pbars) == 1


def _indirectly_decorated(steps=2):
for _i in trange(4):
pass
Expand Down

0 comments on commit e47338a

Please sign in to comment.