Skip to content

Commit d407334

Browse files
authored
Merge pull request #29 from TobiX/contextmanager
Allow usage as a context manager.
2 parents 6553b7b + 086cfd5 commit d407334

3 files changed

Lines changed: 24 additions & 9 deletions

File tree

README.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,17 @@ To use them, just call ``next`` to advance and ``finish`` to finish:
3434
bar.next()
3535
bar.finish()
3636
37+
or use any bar of this class as a context manager:
38+
39+
.. code-block:: python
40+
41+
from progress.bar import Bar
42+
43+
with Bar('Processing', max=20) as bar:
44+
for i in range(20):
45+
# Do some work
46+
bar.next()
47+
3748
The result will be a bar like the following: ::
3849

3950
Processing |############# | 42/100

progress/__init__.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,17 @@ def next(self, n=1):
7373
self.update()
7474

7575
def iter(self, it):
76-
try:
76+
with self:
7777
for x in it:
7878
yield x
7979
self.next()
80-
finally:
81-
self.finish()
80+
81+
def __enter__(self):
82+
self.start()
83+
return self
84+
85+
def __exit__(self, exc_type, exc_val, exc_tb):
86+
self.finish()
8287

8388

8489
class Progress(Infinite):
@@ -119,9 +124,7 @@ def iter(self, it):
119124
except TypeError:
120125
pass
121126

122-
try:
127+
with self:
123128
for x in it:
124129
yield x
125130
self.next()
126-
finally:
127-
self.finish()

test_progress.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@ def sleep():
2727

2828
for bar_cls in (IncrementalBar, PixelBar, ShadyBar):
2929
suffix = '%(percent)d%% [%(elapsed_td)s / %(eta)d / %(eta_td)s]'
30-
bar = bar_cls(bar_cls.__name__, suffix=suffix)
31-
for i in bar.iter(range(200)):
32-
sleep()
30+
with bar_cls(bar_cls.__name__, suffix=suffix, max=200) as bar:
31+
for i in range(200):
32+
bar.next()
33+
sleep()
3334

3435
for spin in (Spinner, PieSpinner, MoonSpinner, LineSpinner, PixelSpinner):
3536
for i in spin(spin.__name__ + ' ').iter(range(100)):

0 commit comments

Comments
 (0)