CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-tqdm

Fast, extensible progress meter for loops and iterators in Python

Overview
Eval results
Files

environments.mddocs/

Environment Variants

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.

Capabilities

Auto-Detection

Automatically selects the best tqdm variant based on the current environment, combining notebook widget support, async capabilities, and standard functionality as needed.

from tqdm.auto import tqdm, trange

# Auto-detected tqdm class with combined capabilities
class tqdm(std_tqdm, notebook_tqdm, asyncio_tqdm):
    """
    Automatically chooses appropriate tqdm subclass based on environment.
    Combines capabilities from notebook, asyncio, and standard implementations.
    """

def trange(*args, **kwargs):
    """Auto-detecting range with progress bar"""

Jupyter Notebook Integration

Widget-based progress bars optimized for Jupyter notebooks and IPython environments with rich HTML display and interactive controls.

from tqdm.notebook import tqdm as notebook_tqdm, trange as notebook_trange

class TqdmHBox(HBox):
    """IPython widget container for progress bar display"""
    def __init__(self, children=(), **kwargs): ...
    
class tqdm_notebook(std_tqdm):
    """
    Jupyter notebook progress bar using IPython widgets.
    
    Provides rich HTML display with color-coded progress bars,
    interactive controls, and integration with notebook output cells.
    """
    def __init__(self, *args, **kwargs): ...
    
    def display(self, msg=None, pos=None, close=False, bar_style=None,
               check_delay=True):
        """Display widget with optional styling and positioning"""
    
    def clear(self, *args, **kwargs):
        """Clear widget display"""
        
    def close(self):
        """Close and cleanup widget"""

def tnrange(*args, **kwargs):
    """Notebook-optimized range with widget progress bar"""

# Aliases for backward compatibility
tqdm = notebook_tqdm
trange = notebook_trange

Async/Await Support

Async-compatible progress bars supporting asyncio patterns including async iteration, as_completed, and gather operations.

from tqdm.asyncio import tqdm as async_tqdm, trange as async_trange

class tqdm_asyncio(std_tqdm):
    """
    Async-compatible progress bar for asyncio applications.
    
    Supports async iteration protocols and integrates with
    common asyncio patterns like as_completed and gather.
    """
    def __init__(self, *args, **kwargs): ...
    
    def __aiter__(self):
        """Async iterator protocol entry point"""
        
    def __anext__(self):
        """Async iterator protocol next method"""
        
    @classmethod
    def as_completed(cls, fs, *, loop=None, timeout=None, total=None, **tqdm_kwargs):
        """
        Wrap asyncio.as_completed with progress tracking.
        
        Parameters:
        - fs: Sequence of awaitables
        - loop: Event loop (deprecated in Python 3.8+)
        - timeout: Maximum time to wait
        - total: Total number of awaitables (auto-detected if None)
        - **tqdm_kwargs: Additional tqdm arguments
        
        Yields:
        Completed futures with progress updates
        """
        
    @classmethod  
    def gather(cls, *fs, loop=None, timeout=None, total=None, **tqdm_kwargs):
        """
        Wrap asyncio.gather with progress tracking.
        
        Parameters:
        - *fs: Awaitables to gather
        - loop: Event loop (deprecated in Python 3.8+) 
        - timeout: Maximum time to wait
        - total: Total awaitables (auto-detected)
        - **tqdm_kwargs: Additional tqdm arguments
        
        Returns:
        List of results from all awaitables
        """

def tarange(*args, **kwargs):
    """Async-compatible range with progress bar"""

# Aliases for backward compatibility  
tqdm = async_tqdm
trange = async_trange

GUI Interfaces

Graphical progress bars using different GUI toolkits for desktop applications and interactive environments.

from tqdm.gui import tqdm as gui_tqdm, trange as gui_trange

class tqdm_gui(std_tqdm):
    """
    Matplotlib-based GUI progress bar.
    
    Creates a popup window with graphical progress bar
    suitable for desktop applications and scripts.
    """
    def __init__(self, *args, **kwargs): ...
    
    def close(self):
        """Close GUI window and cleanup"""

def tgrange(*args, **kwargs):
    """GUI range with matplotlib progress bar"""

# Aliases
tqdm = gui_tqdm  
trange = gui_trange

Tkinter GUI

Native Tkinter-based progress bars for integration with Tkinter applications and cross-platform desktop compatibility.

from tqdm.tk import tqdm as tk_tqdm, trange as tk_trange

class tqdm_tk(std_tqdm):
    """
    Tkinter-based GUI progress bar.
    
    Integrates with Tkinter applications and provides
    native progress bar widgets with cross-platform support.
    """
    def __init__(self, *args, **kwargs): ...
    
    def close(self):
        """Close Tkinter window and cleanup"""

def ttkrange(*args, **kwargs):
    """Tkinter range with native GUI progress bar"""

# Aliases
tqdm = tk_tqdm
trange = tk_trange

Rich Terminal Integration

Enhanced terminal progress bars using the Rich library for improved styling, colors, and terminal capabilities.

from tqdm.rich import tqdm as rich_tqdm, trange as rich_trange

class FractionColumn(ProgressColumn):
    """Rich progress column displaying fraction (n/total)"""
    def render(self, task): ...

class RateColumn(ProgressColumn):  
    """Rich progress column displaying iteration rate"""
    def render(self, task): ...

class tqdm_rich(std_tqdm):
    """
    Rich library integration for enhanced terminal progress bars.
    
    Provides improved styling, colors, and terminal capabilities
    using the Rich library's advanced formatting features.
    """
    def __init__(self, *args, **kwargs): ...

def trrange(*args, **kwargs):
    """Range with Rich-formatted progress bar"""

# Aliases
tqdm = rich_tqdm
trange = rich_trange

Auto-Notebook Detection

Simplified import that automatically detects Jupyter notebook environments and selects appropriate display mode.

from tqdm.autonotebook import tqdm, trange

# Automatically imports from tqdm.notebook in notebooks,
# tqdm.std elsewhere

Usage Examples

Auto-Detection Usage

# Recommended import - works everywhere
from tqdm.auto import tqdm, trange
import asyncio

# Works in notebooks, async contexts, and standard terminals
async def process_data():
    # Async iteration support
    async for item in tqdm(async_data_source(), desc="Processing"):
        await process_item(item)
    
    # Async gather with progress
    tasks = [fetch_data(i) for i in range(100)]
    results = await tqdm.gather(*tasks, desc="Fetching")
    
    return results

# Standard synchronous usage
for i in tqdm(range(1000), desc="Standard Loop"):
    process_item(i)

Jupyter Notebook Usage

from tqdm.notebook import tqdm, trange
import time

# Widget-based progress bar in notebooks
for i in tqdm(range(1000), desc="Notebook Progress"):
    time.sleep(0.001)

# Custom styling in notebooks
for i in tqdm(range(500), desc="Styled", 
              bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt}',
              colour='green'):
    time.sleep(0.002)

# Multiple bars in notebook cells
outer = tqdm(range(10), desc="Outer Loop")
for i in outer:
    inner = tqdm(range(100), desc=f"Inner {i}", leave=False)
    for j in inner:
        time.sleep(0.0001)
    inner.close()
outer.close()

Async Programming Patterns

from tqdm.asyncio import tqdm, trange
import asyncio
import aiohttp

async def fetch_url(session, url):
    async with session.get(url) as response:
        return await response.text()

async def process_urls():
    urls = [f"https://api.example.com/data/{i}" for i in range(100)]
    
    async with aiohttp.ClientSession() as session:
        # Async iteration with progress
        async for url in tqdm(urls, desc="Fetching URLs"):
            content = await fetch_url(session, url)
            process_content(content)
        
        # Async gather with progress tracking
        tasks = [fetch_url(session, url) for url in urls]
        results = await tqdm.gather(*tasks, desc="Batch Fetch", total=len(tasks))
        
        # Async as_completed pattern
        tasks = [fetch_url(session, url) for url in urls]
        async for task in tqdm.as_completed(tasks, desc="As Completed"):
            result = await task
            process_result(result)

# Run async function
asyncio.run(process_urls())

GUI Applications

import tkinter as tk
from tqdm.tk import tqdm, trange
import time
import threading

def long_running_task():
    """Function that runs in background thread with GUI progress"""
    for i in tqdm(range(1000), desc="Processing", leave=True):
        time.sleep(0.01)  # Simulate work

def start_task():
    # Run in separate thread to avoid blocking GUI
    thread = threading.Thread(target=long_running_task)
    thread.daemon = True
    thread.start()

# Create main window
root = tk.Tk()
root.title("Progress Demo")

start_button = tk.Button(root, text="Start Task", command=start_task)
start_button.pack(pady=20)

root.mainloop()

Rich Terminal Enhancement

from tqdm.rich import tqdm, trange
import time

# Enhanced terminal progress with Rich styling
for i in tqdm(range(1000), desc="[bold blue]Processing", 
              bar_format="{desc} {percentage:3.0f}% [{bar:30}] {n_fmt}/{total_fmt}"):
    time.sleep(0.001)

# Multiple styled bars
for epoch in trange(5, desc="[red]Training Epochs"):
    for batch in trange(100, desc="[green]Batches", leave=False):
        time.sleep(0.0001)

Environment-Specific Configuration

import sys

# Choose appropriate tqdm based on environment
if 'ipykernel' in sys.modules:
    # Running in Jupyter notebook
    from tqdm.notebook import tqdm, trange
elif sys.platform.startswith('win'):
    # Windows - may want GUI version
    from tqdm.gui import tqdm, trange  
else:
    # Standard terminal
    from tqdm import tqdm, trange

# Or use auto-detection (recommended)
from tqdm.auto import tqdm, trange

# Your code works the same regardless of environment
for i in tqdm(range(1000), desc="Cross-platform"):
    process_item(i)

Environment Detection

tqdm automatically detects execution environments using these mechanisms:

Jupyter Detection

  • Checks for IPython and ipywidgets availability
  • Detects notebook kernel environment variables
  • Falls back to standard terminal if widgets unavailable

Async Context Detection

  • Inspects current event loop status
  • Integrates with asyncio module presence
  • Maintains compatibility with sync contexts

GUI Availability

  • Tests for matplotlib and tkinter imports
  • Checks display environment variables (DISPLAY, etc.)
  • Graceful fallback to terminal on headless systems

Terminal Capabilities

  • Unicode support detection
  • Color capability testing
  • Screen dimension detection for dynamic sizing

Install with Tessl CLI

npx tessl i tessl/pypi-tqdm

docs

core.md

environments.md

index.md

integrations.md

parallel.md

utilities.md

tile.json