0
# Progress Bar Management
1
2
Advanced progress bar functionality that extends basic logging with support for multiple named progress bars, selective display control, and automatic tracking during iteration. Includes both generic bar management (ProgressBarLogger) and concrete tqdm-powered implementation (TqdmProgressBarLogger) for visual display.
3
4
## Capabilities
5
6
### Generic Progress Bar Logger
7
8
Foundation class for managing multiple named progress bars with filtering and control capabilities.
9
10
```python { .api }
11
class ProgressBarLogger(ProgressLogger):
12
def __init__(self, init_state=None, bars=None, ignored_bars=None,
13
logged_bars="all", min_time_interval=0, ignore_bars_under=0):
14
"""
15
Initialize progress bar logger with bar configuration.
16
17
Parameters:
18
- init_state (dict, optional): Initial state dictionary
19
- bars (None, list, tuple, or dict, optional): Bar configuration
20
* None: Initialize with no bars
21
* list/tuple: Bar names (e.g., ['main', 'sub']) with default settings
22
* dict: Complete bar specifications with titles, indices, totals
23
- ignored_bars (None, list, or "all_others", optional): Bars to ignore
24
* None: All bars are processed
25
* list: Specific bar names to ignore
26
* "all_others": Ignore bars not already in self.bars
27
- logged_bars ("all" or list, optional): Bars to include in logs
28
- min_time_interval (float): Minimum seconds between bar updates
29
- ignore_bars_under (int): Ignore bars with fewer than N items
30
"""
31
```
32
33
**Usage Example:**
34
35
```python
36
from proglog import ProgressBarLogger
37
38
# Basic bar logger
39
logger = ProgressBarLogger()
40
41
# Pre-configured bars
42
logger = ProgressBarLogger(bars=["main", "subtask"])
43
44
# Detailed bar configuration
45
bars_config = {
46
"main": {"title": "Main Task", "index": 0, "total": 100},
47
"sub": {"title": "Subtask", "index": -1, "total": None}
48
}
49
logger = ProgressBarLogger(bars=bars_config)
50
51
# Selective bar display
52
logger = ProgressBarLogger(
53
ignored_bars=["debug"], # Don't show debug bars
54
logged_bars=["main"], # Only log main bar
55
min_time_interval=0.1 # Update at most every 100ms
56
)
57
```
58
59
### Bar Iteration
60
61
Automatically track progress while iterating through data with bar updates.
62
63
```python { .api }
64
def iter_bar(self, bar_prefix="", **kw):
65
"""
66
Iterate through data while updating a progress bar.
67
68
Parameters:
69
- bar_prefix (str): Prefix to add to bar name
70
- **kw: Single key-value pair where key is bar name and value is iterable
71
- bar_message (optional): Function to generate message from current item
72
73
Returns:
74
Iterator that yields items while updating progress bar
75
"""
76
```
77
78
**Usage Example:**
79
80
```python
81
logger = ProgressBarLogger()
82
83
# Basic bar iteration
84
for item in logger.iter_bar(processing=range(100)):
85
# Bar "processing" automatically updates from 0 to 99
86
process_item(item)
87
88
# Nested bars with prefixes
89
for i in logger.iter_bar(main=range(10)):
90
for j in logger.iter_bar("sub_", task=["a", "b", "c"]):
91
# Creates bars "main" and "sub_task"
92
do_work(i, j)
93
94
# Dynamic messages
95
def message_func(item):
96
return f"Processing {item}"
97
98
for file in logger.iter_bar(files=file_list, bar_message=message_func):
99
process_file(file)
100
```
101
102
### Bar State Management
103
104
Direct control over bar attributes and behavior.
105
106
```python { .api }
107
@property
108
def bars(self):
109
"""Access the bars state dictionary."""
110
111
def bar_is_ignored(self, bar):
112
"""
113
Check if a bar should be ignored.
114
115
Parameters:
116
- bar (str): Bar name
117
118
Returns:
119
bool: True if bar should be ignored
120
"""
121
122
def bar_is_logged(self, bar):
123
"""
124
Check if a bar should be logged.
125
126
Parameters:
127
- bar (str): Bar name
128
129
Returns:
130
bool: True if bar should be logged
131
"""
132
133
def bars_callback(self, bar, attr, value, old_value=None):
134
"""
135
Custom callback for bar updates.
136
137
Override in subclasses for custom bar update behavior.
138
139
Parameters:
140
- bar (str): Bar name
141
- attr (str): Attribute being updated ("index", "total", "message")
142
- value: New value
143
- old_value: Previous value
144
"""
145
```
146
147
**Usage Example:**
148
149
```python
150
# Manual bar updates using __call__
151
logger = ProgressBarLogger()
152
153
# Set bar total
154
logger(main__total=100)
155
156
# Update bar progress
157
for i in range(100):
158
logger(main__index=i, main__message=f"Step {i}")
159
do_work()
160
161
# Access bar state
162
print(logger.bars) # Shows all bar configurations
163
print(logger.bar_is_ignored("main")) # False
164
```
165
166
### Tqdm Progress Bar Logger
167
168
Concrete implementation using tqdm library for visual progress bar display in console and Jupyter notebooks.
169
170
```python { .api }
171
class TqdmProgressBarLogger(ProgressBarLogger):
172
def __init__(self, init_state=None, bars=None, leave_bars=False,
173
ignored_bars=None, logged_bars="all", notebook="default",
174
print_messages=True, min_time_interval=0, ignore_bars_under=0):
175
"""
176
Initialize tqdm-powered progress bar logger.
177
178
Parameters:
179
- init_state (dict, optional): Initial state dictionary
180
- bars: Bar configuration (same as ProgressBarLogger)
181
- leave_bars (bool): Whether to leave bars displayed after completion
182
- ignored_bars: Bars to ignore (same as ProgressBarLogger)
183
- logged_bars: Bars to log (same as ProgressBarLogger)
184
- notebook ("default", True, or False): Notebook display mode
185
* "default": Use global notebook setting
186
* True: Force notebook-style HTML bars
187
* False: Use console-style bars
188
- print_messages (bool): Whether to print logger messages
189
- min_time_interval (float): Minimum seconds between updates
190
- ignore_bars_under (int): Ignore iterables with fewer items
191
"""
192
```
193
194
**Usage Example:**
195
196
```python
197
from proglog import TqdmProgressBarLogger
198
import time
199
200
# Console progress bars
201
logger = TqdmProgressBarLogger()
202
203
# Jupyter notebook optimized bars
204
logger = TqdmProgressBarLogger(notebook=True, leave_bars=True)
205
206
# Customized behavior
207
logger = TqdmProgressBarLogger(
208
ignored_bars=["debug"], # Don't show debug bars
209
print_messages=False, # Suppress message printing
210
min_time_interval=0.05, # Update every 50ms
211
ignore_bars_under=5 # Skip bars with <5 items
212
)
213
214
# Usage with automatic tqdm display
215
for i in logger.iter_bar(main=range(100)):
216
for j in logger.iter_bar(sub=range(20)):
217
time.sleep(0.01)
218
if i % 20 == 0:
219
logger(message=f"Completed batch {i//20}")
220
```
221
222
### Tqdm Bar Management
223
224
Advanced control over tqdm bar creation and lifecycle.
225
226
```python { .api }
227
def new_tqdm_bar(self, bar):
228
"""
229
Create a new tqdm progress bar.
230
231
Parameters:
232
- bar (str): Bar name
233
"""
234
235
def close_tqdm_bar(self, bar):
236
"""
237
Close and cleanup a tqdm progress bar.
238
239
Parameters:
240
- bar (str): Bar name
241
"""
242
```
243
244
**Usage Example:**
245
246
```python
247
logger = TqdmProgressBarLogger()
248
249
# Manual bar lifecycle management
250
logger.bars["custom"] = {
251
"title": "Custom Task",
252
"index": 0,
253
"total": 50,
254
"message": "Starting"
255
}
256
logger.new_tqdm_bar("custom")
257
258
# Update bar manually
259
for i in range(50):
260
logger(custom__index=i, custom__message=f"Item {i}")
261
time.sleep(0.1)
262
263
logger.close_tqdm_bar("custom")
264
```
265
266
## Silent Progress Bar Logger
267
268
Special logger that suppresses all progress bar display while maintaining the same API.
269
270
```python { .api }
271
class MuteProgressBarLogger(ProgressBarLogger):
272
"""
273
Silent progress bar logger that ignores all bars.
274
275
Provides the same API as ProgressBarLogger but suppresses
276
all visual output. Useful for silent operation modes.
277
"""
278
279
def bar_is_ignored(self, bar):
280
"""Always returns True - all bars are ignored."""
281
```
282
283
**Usage Example:**
284
285
```python
286
from proglog import MuteProgressBarLogger
287
288
# Silent operation - no progress bars displayed
289
logger = MuteProgressBarLogger()
290
291
# Same API as other loggers, but no visual output
292
for item in logger.iter_bar(processing=data):
293
process_item(item) # No progress bar shown
294
295
# State tracking still works
296
logger(progress=50)
297
print(logger.state) # {'progress': 50}
298
```
299
300
## Bar Configuration Format
301
302
### Bar Dictionary Structure
303
304
```python { .api }
305
# Bar configuration dictionary format
306
bar_config = {
307
"title": str, # Display title for the bar
308
"index": int, # Current position (-1 for unstarted)
309
"total": int, # Total items (None for indeterminate)
310
"message": str, # Current status message (None for no message)
311
"indent": int # Log indentation level
312
}
313
```
314
315
### Update Syntax
316
317
Progress bar updates use double-underscore syntax in logger calls:
318
319
```python
320
# Bar attribute updates
321
logger(barname__total=100) # Set total items
322
logger(barname__index=50) # Update current position
323
logger(barname__message="Processing...") # Set status message
324
325
# Multiple bar updates
326
logger(
327
main__index=10,
328
sub__total=20,
329
sub__index=5,
330
sub__message="Subtask running"
331
)
332
```