Skip to content

Register now for

# Reference for `ultralytics/utils/tqdm.py`

Note

This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/utils/tqdm.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!

## `` ultralytics.utils.tqdm.TQDM

    TQDM(
        iterable: Any = None,
        desc: str | None = None,
        total: int | None = None,
        leave: bool = True,
        file: IO[str] | None = None,
        mininterval: float = 0.1,
        disable: bool | None = None,
        unit: str = "it",
        unit_scale: bool = True,
        unit_divisor: int = 1000,
        bar_format: str | None = None,
        initial: int = 0,
        **kwargs
    )

Lightweight zero-dependency progress bar for Ultralytics.

Provides clean, rich-style progress bars suitable for various environments including Weights & Biases, console outputs, and other logging systems. Features zero external dependencies, clean single-line output, rich-style progress bars with Unicode block characters, context manager support, iterator protocol support, and dynamic description updates.

Attributes:

Name | Type | Description
--- | --- | ---
`iterable` | `object` | Iterable to wrap with progress bar.
`desc` | `str` | Prefix description for the progress bar.
`total` | `int` | Expected number of iterations.
`disable` | `bool` | Whether to disable the progress bar.
`unit` | `str` | String for units of iteration.
`unit_scale` | `bool` | Auto-scale units flag.
`unit_divisor` | `int` | Divisor for unit scaling.
`leave` | `bool` | Whether to leave the progress bar after completion.
`mininterval` | `float` | Minimum time interval between updates.
`initial` | `int` | Initial counter value.
`n` | `int` | Current iteration count.
`closed` | `bool` | Whether the progress bar is closed.
`bar_format` | `str` | Custom bar format string.
`file` | `object` | Output file stream.

Methods:

Name | Description
--- | ---
`update` | Update progress by n steps.
`set_description` | Set or update the description.
`set_postfix` | Set postfix for the progress bar.
`close` | Close the progress bar and clean up.
`refresh` | Refresh the progress bar display.
`clear` | Clear the progress bar from display.
`write` | Write a message without breaking the progress bar.

Examples:

Basic usage with iterator:

    >>> for i in TQDM(range(100)):
    ...     time.sleep(0.01)

With custom description:

    >>> pbar = TQDM(range(100), desc="Processing")
    >>> for i in pbar:
    ...     pbar.set_description(f"Processing item {i}")

Context manager usage:

    >>> with TQDM(total=100, unit="B", unit_scale=True) as pbar:
    ...     for i in range(100):
    ...         pbar.update(1)

Manual updates:

    >>> pbar = TQDM(total=100, desc="Training")
    >>> for epoch in range(100):
    ...     # Do work
    ...     pbar.update(1)
    >>> pbar.close()

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`iterable` | `object` | Iterable to wrap with progress bar. | `None`
`desc` | `str` | Prefix description for the progress bar. | `None`
`total` | `int` | Expected number of iterations. | `None`
`leave` | `bool` | Whether to leave the progress bar after completion. | `True`
`file` | `object` | Output file stream for progress display. | `None`
`mininterval` | `float` | Minimum time interval between updates (default 0.1s, 60s in GitHub Actions). | `0.1`
`disable` | `bool` | Whether to disable the progress bar. Auto-detected if None. | `None`
`unit` | `str` | String for units of iteration (default "it" for items). | `'it'`
`unit_scale` | `bool` | Auto-scale units for bytes/data units. | `True`
`unit_divisor` | `int` | Divisor for unit scaling (default 1000). | `1000`
`bar_format` | `str` | Custom bar format string. | `None`
`initial` | `int` | Initial counter value. | `0`
`**kwargs` | `Any` | Additional keyword arguments for compatibility (ignored). | `{}`

Examples:

    >>> pbar = TQDM(range(100), desc="Processing")
    >>> with TQDM(total=1000, unit="B", unit_scale=True) as pbar:
    ...     pbar.update(1024)  # Updates by 1KB

Source code in `ultralytics/utils/tqdm.py`

     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    def __init__(
        self,
        iterable: Any = None,
        desc: str | None = None,
        total: int | None = None,
        leave: bool = True,
        file: IO[str] | None = None,
        mininterval: float = 0.1,
        disable: bool | None = None,
        unit: str = "it",
        unit_scale: bool = True,
        unit_divisor: int = 1000,
        bar_format: str | None = None,  # kept for API compatibility; not used for formatting
        initial: int = 0,
        **kwargs,
    ) -> None:
        """
        Initialize the TQDM progress bar with specified configuration options.

        Args:
            iterable (object, optional): Iterable to wrap with progress bar.
            desc (str, optional): Prefix description for the progress bar.
            total (int, optional): Expected number of iterations.
            leave (bool, optional): Whether to leave the progress bar after completion.
            file (object, optional): Output file stream for progress display.
            mininterval (float, optional): Minimum time interval between updates (default 0.1s, 60s in GitHub Actions).
            disable (bool, optional): Whether to disable the progress bar. Auto-detected if None.
            unit (str, optional): String for units of iteration (default "it" for items).
            unit_scale (bool, optional): Auto-scale units for bytes/data units.
            unit_divisor (int, optional): Divisor for unit scaling (default 1000).
            bar_format (str, optional): Custom bar format string.
            initial (int, optional): Initial counter value.
            **kwargs (Any): Additional keyword arguments for compatibility (ignored).

        Examples:
            >>> pbar = TQDM(range(100), desc="Processing")
            >>> with TQDM(total=1000, unit="B", unit_scale=True) as pbar:
            ...     pbar.update(1024)  # Updates by 1KB
        """
        # Disable if not verbose
        if disable is None:
            try:
                from ultralytics.utils import LOGGER, VERBOSE

                disable = not VERBOSE or LOGGER.getEffectiveLevel() > 20
            except ImportError:
                disable = False

        self.iterable = iterable
        self.desc = desc or ""
        self.total = total or (len(iterable) if hasattr(iterable, "__len__") else None) or None  # prevent total=0
        self.disable = disable
        self.unit = unit
        self.unit_scale = unit_scale
        self.unit_divisor = unit_divisor
        self.leave = leave
        self.noninteractive = is_noninteractive_console()
        self.mininterval = max(mininterval, self.NONINTERACTIVE_MIN_INTERVAL) if self.noninteractive else mininterval
        self.initial = initial

        # Kept for API compatibility (unused for f-string formatting)
        self.bar_format = bar_format

        self.file = file or sys.stdout

        # Internal state
        self.n = self.initial
        self.last_print_n = self.initial
        self.last_print_t = time.time()
        self.start_t = time.time()
        self.last_rate = 0.0
        self.closed = False
        self.is_bytes = unit_scale and unit in ("B", "bytes")
        self.scales = (
            [(1073741824, "GB/s"), (1048576, "MB/s"), (1024, "KB/s")]
            if self.is_bytes
            else [(1e9, f"G{self.unit}/s"), (1e6, f"M{self.unit}/s"), (1e3, f"K{self.unit}/s")]
        )

        if not self.disable and self.total and not self.noninteractive:
            self._display()

### `` __del__

    __del__() -> None

Destructor to ensure cleanup.

Source code in `ultralytics/utils/tqdm.py`

    353
    354
    355
    356
    357
    358
    def __del__(self) -> None:
        """Destructor to ensure cleanup."""
        try:
            self.close()
        except Exception:
            pass

### `` __enter__

    __enter__() -> TQDM

Enter context manager.

Source code in `ultralytics/utils/tqdm.py`

    333
    334
    335
    def __enter__(self) -> TQDM:
        """Enter context manager."""
        return self

### `` __exit__

    __exit__(*args: Any) -> None

Exit context manager and close progress bar.

Source code in `ultralytics/utils/tqdm.py`

    337
    338
    339
    def __exit__(self, *args: Any) -> None:
        """Exit context manager and close progress bar."""
        self.close()

### `` __iter__

    __iter__() -> Any

Iterate over the wrapped iterable with progress updates.

Source code in `ultralytics/utils/tqdm.py`

    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    def __iter__(self) -> Any:
        """Iterate over the wrapped iterable with progress updates."""
        if self.iterable is None:
            raise TypeError("'NoneType' object is not iterable")

        try:
            for item in self.iterable:
                yield item
                self.update(1)
        finally:
            self.close()

### `` clear

    clear() -> None

Clear progress bar.

Source code in `ultralytics/utils/tqdm.py`

    365
    366
    367
    368
    369
    370
    371
    372
    def clear(self) -> None:
        """Clear progress bar."""
        if not self.disable:
            try:
                self.file.write("\r\033[K")
                self.file.flush()
            except Exception:
                pass

### `` close

    close() -> None

Close progress bar.

Source code in `ultralytics/utils/tqdm.py`

    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    def close(self) -> None:
        """Close progress bar."""
        if self.closed:
            return

        self.closed = True

        if not self.disable:
            # Final display
            if self.total and self.n >= self.total:
                self.n = self.total
            self._display(final=True)

            # Cleanup
            if self.leave:
                self.file.write("\n")
            else:
                self.file.write("\r\033[K")

            try:
                self.file.flush()
            except Exception:
                pass

### `` refresh

    refresh() -> None

Refresh display.

Source code in `ultralytics/utils/tqdm.py`

    360
    361
    362
    363
    def refresh(self) -> None:
        """Refresh display."""
        if not self.disable:
            self._display()

### `` set_description

    set_description(desc: str | None) -> None

Set description.

Source code in `ultralytics/utils/tqdm.py`

    296
    297
    298
    299
    300
    def set_description(self, desc: str | None) -> None:
        """Set description."""
        self.desc = desc or ""
        if not self.disable:
            self._display()

### `` set_postfix

    set_postfix(**kwargs: Any) -> None

Set postfix (appends to description).

Source code in `ultralytics/utils/tqdm.py`

    302
    303
    304
    305
    306
    307
    def set_postfix(self, **kwargs: Any) -> None:
        """Set postfix (appends to description)."""
        if kwargs:
            postfix = ", ".join(f"{k}={v}" for k, v in kwargs.items())
            base_desc = self.desc.split(" | ")[0] if " | " in self.desc else self.desc
            self.set_description(f"{base_desc} | {postfix}")

### `` update

    update(n: int = 1) -> None

Update progress by n steps.

Source code in `ultralytics/utils/tqdm.py`

    290
    291
    292
    293
    294
    def update(self, n: int = 1) -> None:
        """Update progress by n steps."""
        if not self.disable and not self.closed:
            self.n += n
            self._display()

### `` write `staticmethod`

    write(s: str, file: IO[str] | None = None, end: str = '\n') -> None

Static method to write without breaking progress bar.

Source code in `ultralytics/utils/tqdm.py`

    374
    375
    376
    377
    378
    379
    380
    381
    382
    @staticmethod
    def write(s: str, file: IO[str] | None = None, end: str = "\n") -> None:
        """Static method to write without breaking progress bar."""
        file = file or sys.stdout
        try:
            file.write(s + end)
            file.flush()
        except Exception:
            pass

## `` ultralytics.utils.tqdm.is_noninteractive_console `cached`

    is_noninteractive_console() -> bool

Check for known non-interactive console environments.

Source code in `ultralytics/utils/tqdm.py`

    12
    13
    14
    15
    @lru_cache(maxsize=1)
    def is_noninteractive_console() -> bool:
        """Check for known non-interactive console environments."""
        return "GITHUB_ACTIONS" in os.environ or "RUNPOD_POD_ID" in os.environ

📅 Created 25 days ago ✏️ Updated 25 days ago