Skip to content
Myr

Restore progressbar iterator interface; add test

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- add a test for iterating on a progressbar with next() - implement `next()` in terms of `iter(ProgressBar)`, which is already well-defined - add a note about slow operations with progressbar to narrative docs One of the keys to this working is that `ProgressBar.generator` is consuming an iterable and doesn't store any important state in local variables, making it re-entry safe. I wasn't sure how we can best hint in the public docs that simply walking the bar and stopping one step short of finishing will result in the progress bar "hanging" unfinished. Noting that we work well with things like `time.sleep()` seems like a decent way of advertising positively something which we support *and* guiding anyone going off-book into proper usage. closes #1125

authored by Stephen Rosen · committed by David Lord · parent 22366a6 · Browse files · 4 files+54 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+54 added−4 removed

  • tests:+20 added−0 removed
  • other:+34 added−4 removed

4 files+54 added−4 removed

modified:click/_termui_impl.py+21 added-4 removed
106 unmodified lines
107 raise RuntimeError('You need to use progress bars in a with block.')108 self.render_progress()109 return self.generator()110111 def __next__(self):112 # Iteration is defined in terms of a generator function,113 # returned by iter(self); use that to define next(). This works114 # because `self.iter` is an iterable consumed by that generator,115 # so it is re-entry safe. Calling `next(self.generator())`116 # twice works and does "what you want".117 return next(iter(self))118119 # Python 2 compat120 next = __next__121122 def is_fast(self):123 return time.time() - self.start <= self.short_limit124125 def render_finish(self):
154 unmodified lines
280 self.current_item = None281 self.finished = True282283 def generator(self):284 """Return a generator which yields the items added to the bar285 during construction, and updates the progress bar *after* the286 yielded block returns.287 """274 Returns a generator which yields the items added to the bar during275 construction, and updates the progress bar *after* the yielded block276 returns.277 """288 # WARNING: the iterator interface for `ProgressBar` relies on289 # this and only works because this is a simple generator which290 # doesn't create or manage additional state. If this function291 # changes, the impact should be evaluated both against292 # `iter(bar)` and `next(bar)`. `next()` in particular may call293 # `self.generator()` repeatedly, and this must remain safe in294 # order for that interface to work.295 if not self.entered:296 raise RuntimeError('You need to use progress bars in a with block.')297298 if self.is_hidden:
340 unmodified lines
modified:docs/utils.rst+10 added
387 unmodified lines
388 length=number_of_users) as bar:389 for user in bar:390 modify_the_user(user)391392Note that :func:`progressbar` updates the bar *after* each iteration of the393loop. So code like this will render correctly::394395 import time396397 with click.progressbar([1, 2, 3]) as bar:398 for x in bar:399 print('sleep({})...'.format(x))400 time.sleep(x)401402Another useful feature is to associate a label with the progress bar which403will be shown preceding the progress bar::404405 with click.progressbar(all_the_users_to_process,
15 unmodified lines
modified:tests/test_termui.py+20 added
183 unmodified lines
184 else:185 assert False, 'Expected an exception because of abort-related inputs.'186187188def test_progressbar_is_iterator(runner, monkeypatch):189 fake_clock = FakeClock()190191 @click.command()192 def cli():193 with click.progressbar(range(10), label='test') as progress:194 while True:195 try:196 next(progress)197 fake_clock.advance_time()198 except StopIteration:199 break200201 monkeypatch.setattr(time, 'time', fake_clock.time)202 monkeypatch.setattr(click._termui_impl, 'isatty', lambda _: True)203204 result = runner.invoke(cli, [])205 assert result.exception is None206207208def test_choices_list_in_prompt(runner, monkeypatch):209 @click.command()210 @click.option('-g', type=click.Choice(['none', 'day', 'week', 'month']),211 prompt=True)
84 unmodified lines
modified:CHANGES.rst+3 added
25 unmodified lines
26- Add ``show_defaults`` parameter to ``Context`` to enable showing27 defaults globally. :issue:`1018`28- Handle ``env MYPATH=''`` as though the option were not passed.29 :issue:`1196`30- It is once again possible to call ``next(bar)`` on an active31 progress bar instance. :issue:`1125`323334Version 7.035-----------3637Released 2018-09-25
538 unmodified lines