0
# Environment Variants
1
2
Specialized progress bar implementations optimized for different execution environments. tqdm automatically detects the best variant to use, or you can explicitly choose based on your specific requirements.
3
4
## Capabilities
5
6
### Auto-Detection
7
8
Automatically selects the best tqdm variant based on the current environment, combining notebook widget support, async capabilities, and standard functionality as needed.
9
10
```python { .api }
11
from tqdm.auto import tqdm, trange
12
13
# Auto-detected tqdm class with combined capabilities
14
class tqdm(std_tqdm, notebook_tqdm, asyncio_tqdm):
15
"""
16
Automatically chooses appropriate tqdm subclass based on environment.
17
Combines capabilities from notebook, asyncio, and standard implementations.
18
"""
19
20
def trange(*args, **kwargs):
21
"""Auto-detecting range with progress bar"""
22
```
23
24
### Jupyter Notebook Integration
25
26
Widget-based progress bars optimized for Jupyter notebooks and IPython environments with rich HTML display and interactive controls.
27
28
```python { .api }
29
from tqdm.notebook import tqdm as notebook_tqdm, trange as notebook_trange
30
31
class TqdmHBox(HBox):
32
"""IPython widget container for progress bar display"""
33
def __init__(self, children=(), **kwargs): ...
34
35
class tqdm_notebook(std_tqdm):
36
"""
37
Jupyter notebook progress bar using IPython widgets.
38
39
Provides rich HTML display with color-coded progress bars,
40
interactive controls, and integration with notebook output cells.
41
"""
42
def __init__(self, *args, **kwargs): ...
43
44
def display(self, msg=None, pos=None, close=False, bar_style=None,
45
check_delay=True):
46
"""Display widget with optional styling and positioning"""
47
48
def clear(self, *args, **kwargs):
49
"""Clear widget display"""
50
51
def close(self):
52
"""Close and cleanup widget"""
53
54
def tnrange(*args, **kwargs):
55
"""Notebook-optimized range with widget progress bar"""
56
57
# Aliases for backward compatibility
58
tqdm = notebook_tqdm
59
trange = notebook_trange
60
```
61
62
### Async/Await Support
63
64
Async-compatible progress bars supporting asyncio patterns including async iteration, `as_completed`, and `gather` operations.
65
66
```python { .api }
67
from tqdm.asyncio import tqdm as async_tqdm, trange as async_trange
68
69
class tqdm_asyncio(std_tqdm):
70
"""
71
Async-compatible progress bar for asyncio applications.
72
73
Supports async iteration protocols and integrates with
74
common asyncio patterns like as_completed and gather.
75
"""
76
def __init__(self, *args, **kwargs): ...
77
78
def __aiter__(self):
79
"""Async iterator protocol entry point"""
80
81
def __anext__(self):
82
"""Async iterator protocol next method"""
83
84
@classmethod
85
def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs):
86
"""
87
Wrap asyncio.as_completed with progress tracking.
88
89
Parameters:
90
- fs: Sequence of awaitables
91
- loop: Event loop (deprecated in Python 3.8+)
92
- timeout: Maximum time to wait
93
- total: Total number of awaitables (auto-detected if None)
94
- **tqdm_kwargs: Additional tqdm arguments
95
96
Yields:
97
Completed futures with progress updates
98
"""
99
100
@classmethod
101
def gather(cls, *fs, loop=None, timeout=None, total=None, **tqdm_kwargs):
102
"""
103
Wrap asyncio.gather with progress tracking.
104
105
Parameters:
106
- *fs: Awaitables to gather
107
- loop: Event loop (deprecated in Python 3.8+)
108
- timeout: Maximum time to wait
109
- total: Total awaitables (auto-detected)
110
- **tqdm_kwargs: Additional tqdm arguments
111
112
Returns:
113
List of results from all awaitables
114
"""
115
116
def tarange(*args, **kwargs):
117
"""Async-compatible range with progress bar"""
118
119
# Aliases for backward compatibility
120
tqdm = async_tqdm
121
trange = async_trange
122
```
123
124
### GUI Interfaces
125
126
Graphical progress bars using different GUI toolkits for desktop applications and interactive environments.
127
128
```python { .api }
129
from tqdm.gui import tqdm as gui_tqdm, trange as gui_trange
130
131
class tqdm_gui(std_tqdm):
132
"""
133
Matplotlib-based GUI progress bar.
134
135
Creates a popup window with graphical progress bar
136
suitable for desktop applications and scripts.
137
"""
138
def __init__(self, *args, **kwargs): ...
139
140
def close(self):
141
"""Close GUI window and cleanup"""
142
143
def tgrange(*args, **kwargs):
144
"""GUI range with matplotlib progress bar"""
145
146
# Aliases
147
tqdm = gui_tqdm
148
trange = gui_trange
149
```
150
151
### Tkinter GUI
152
153
Native Tkinter-based progress bars for integration with Tkinter applications and cross-platform desktop compatibility.
154
155
```python { .api }
156
from tqdm.tk import tqdm as tk_tqdm, trange as tk_trange
157
158
class tqdm_tk(std_tqdm):
159
"""
160
Tkinter-based GUI progress bar.
161
162
Integrates with Tkinter applications and provides
163
native progress bar widgets with cross-platform support.
164
"""
165
def __init__(self, *args, **kwargs): ...
166
167
def close(self):
168
"""Close Tkinter window and cleanup"""
169
170
def ttkrange(*args, **kwargs):
171
"""Tkinter range with native GUI progress bar"""
172
173
# Aliases
174
tqdm = tk_tqdm
175
trange = tk_trange
176
```
177
178
### Rich Terminal Integration
179
180
Enhanced terminal progress bars using the Rich library for improved styling, colors, and terminal capabilities.
181
182
```python { .api }
183
from tqdm.rich import tqdm as rich_tqdm, trange as rich_trange
184
185
class FractionColumn(ProgressColumn):
186
"""Rich progress column displaying fraction (n/total)"""
187
def render(self, task): ...
188
189
class RateColumn(ProgressColumn):
190
"""Rich progress column displaying iteration rate"""
191
def render(self, task): ...
192
193
class tqdm_rich(std_tqdm):
194
"""
195
Rich library integration for enhanced terminal progress bars.
196
197
Provides improved styling, colors, and terminal capabilities
198
using the Rich library's advanced formatting features.
199
"""
200
def __init__(self, *args, **kwargs): ...
201
202
def trrange(*args, **kwargs):
203
"""Range with Rich-formatted progress bar"""
204
205
# Aliases
206
tqdm = rich_tqdm
207
trange = rich_trange
208
```
209
210
### Auto-Notebook Detection
211
212
Simplified import that automatically detects Jupyter notebook environments and selects appropriate display mode.
213
214
```python { .api }
215
from tqdm.autonotebook import tqdm, trange
216
217
# Automatically imports from tqdm.notebook in notebooks,
218
# tqdm.std elsewhere
219
```
220
221
## Usage Examples
222
223
### Auto-Detection Usage
224
225
```python
226
# Recommended import - works everywhere
227
from tqdm.auto import tqdm, trange
228
import asyncio
229
230
# Works in notebooks, async contexts, and standard terminals
231
async def process_data():
232
# Async iteration support
233
async for item in tqdm(async_data_source(), desc="Processing"):
234
await process_item(item)
235
236
# Async gather with progress
237
tasks = [fetch_data(i) for i in range(100)]
238
results = await tqdm.gather(*tasks, desc="Fetching")
239
240
return results
241
242
# Standard synchronous usage
243
for i in tqdm(range(1000), desc="Standard Loop"):
244
process_item(i)
245
```
246
247
### Jupyter Notebook Usage
248
249
```python
250
from tqdm.notebook import tqdm, trange
251
import time
252
253
# Widget-based progress bar in notebooks
254
for i in tqdm(range(1000), desc="Notebook Progress"):
255
time.sleep(0.001)
256
257
# Custom styling in notebooks
258
for i in tqdm(range(500), desc="Styled",
259
bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt}',
260
colour='green'):
261
time.sleep(0.002)
262
263
# Multiple bars in notebook cells
264
outer = tqdm(range(10), desc="Outer Loop")
265
for i in outer:
266
inner = tqdm(range(100), desc=f"Inner {i}", leave=False)
267
for j in inner:
268
time.sleep(0.0001)
269
inner.close()
270
outer.close()
271
```
272
273
### Async Programming Patterns
274
275
```python
276
from tqdm.asyncio import tqdm, trange
277
import asyncio
278
import aiohttp
279
280
async def fetch_url(session, url):
281
async with session.get(url) as response:
282
return await response.text()
283
284
async def process_urls():
285
urls = [f"https://api.example.com/data/{i}" for i in range(100)]
286
287
async with aiohttp.ClientSession() as session:
288
# Async iteration with progress
289
async for url in tqdm(urls, desc="Fetching URLs"):
290
content = await fetch_url(session, url)
291
process_content(content)
292
293
# Async gather with progress tracking
294
tasks = [fetch_url(session, url) for url in urls]
295
results = await tqdm.gather(*tasks, desc="Batch Fetch", total=len(tasks))
296
297
# Async as_completed pattern
298
tasks = [fetch_url(session, url) for url in urls]
299
async for task in tqdm.as_completed(tasks, desc="As Completed"):
300
result = await task
301
process_result(result)
302
303
# Run async function
304
asyncio.run(process_urls())
305
```
306
307
### GUI Applications
308
309
```python
310
import tkinter as tk
311
from tqdm.tk import tqdm, trange
312
import time
313
import threading
314
315
def long_running_task():
316
"""Function that runs in background thread with GUI progress"""
317
for i in tqdm(range(1000), desc="Processing", leave=True):
318
time.sleep(0.01) # Simulate work
319
320
def start_task():
321
# Run in separate thread to avoid blocking GUI
322
thread = threading.Thread(target=long_running_task)
323
thread.daemon = True
324
thread.start()
325
326
# Create main window
327
root = tk.Tk()
328
root.title("Progress Demo")
329
330
start_button = tk.Button(root, text="Start Task", command=start_task)
331
start_button.pack(pady=20)
332
333
root.mainloop()
334
```
335
336
### Rich Terminal Enhancement
337
338
```python
339
from tqdm.rich import tqdm, trange
340
import time
341
342
# Enhanced terminal progress with Rich styling
343
for i in tqdm(range(1000), desc="[bold blue]Processing",
344
bar_format="{desc} {percentage:3.0f}% [{bar:30}] {n_fmt}/{total_fmt}"):
345
time.sleep(0.001)
346
347
# Multiple styled bars
348
for epoch in trange(5, desc="[red]Training Epochs"):
349
for batch in trange(100, desc="[green]Batches", leave=False):
350
time.sleep(0.0001)
351
```
352
353
### Environment-Specific Configuration
354
355
```python
356
import sys
357
358
# Choose appropriate tqdm based on environment
359
if 'ipykernel' in sys.modules:
360
# Running in Jupyter notebook
361
from tqdm.notebook import tqdm, trange
362
elif sys.platform.startswith('win'):
363
# Windows - may want GUI version
364
from tqdm.gui import tqdm, trange
365
else:
366
# Standard terminal
367
from tqdm import tqdm, trange
368
369
# Or use auto-detection (recommended)
370
from tqdm.auto import tqdm, trange
371
372
# Your code works the same regardless of environment
373
for i in tqdm(range(1000), desc="Cross-platform"):
374
process_item(i)
375
```
376
377
## Environment Detection
378
379
tqdm automatically detects execution environments using these mechanisms:
380
381
### Jupyter Detection
382
- Checks for `IPython` and `ipywidgets` availability
383
- Detects notebook kernel environment variables
384
- Falls back to standard terminal if widgets unavailable
385
386
### Async Context Detection
387
- Inspects current event loop status
388
- Integrates with `asyncio` module presence
389
- Maintains compatibility with sync contexts
390
391
### GUI Availability
392
- Tests for `matplotlib` and `tkinter` imports
393
- Checks display environment variables (DISPLAY, etc.)
394
- Graceful fallback to terminal on headless systems
395
396
### Terminal Capabilities
397
- Unicode support detection
398
- Color capability testing
399
- Screen dimension detection for dynamic sizing