Skip to content

API Reference

Tag

A named status tag with an optional color and status value.

Parameters:

Name Type Description Default
name str

Tag identifier, also used as display label in the legend.

required
color str

Color for bar segments and legend swatch. Accepts named colors ("red", "yellow", …) or hex strings ("#ff4444"). Defaults to None (inherits bar color).

None
status int

Integer used to rank tags when multiple items share one bar segment. Higher values take priority with reduce_op=max (the default). Auto-assigned (next available integer) if omitted.

None

TqdmTag

Bases: tqdm

format_dict property

Public API for read-only member access.

__init__(iterable=None, total=None, colour=None, default_status=0, default_tag_name='default', tags=None, initial_status=None, reduce_op=max, reduce_ignore_default=False, legend=False, legend_format=None, legend_show_default=False, prune_legend=False, **kwargs)

A tqdm progress bar whose segments are colored by per-item tags.

Each iteration starts at default_status; calling tag() during the loop body records a different status for the current item. When the bar is rendered, each displayed segment's color is derived from the statuses of the items it represents (via reduce_op), using the color registered for the corresponding tag.

Parameters:

Name Type Description Default
iterable iterable

Iterable to decorate, same as in tqdm.

None
total int

Expected number of iterations, same as in tqdm.

None
colour str

Default bar colour, used for items still at default_status.

None
default_status int

Status value assigned to every item before tag() is called on it (default 0).

0
default_tag_name str

Name of the implicit tag representing default_status, used as its key in tag_to_status/tag_to_color and its label in the legend (default "default"). Change this if "default" collides with a tag name you want to use, or to give the untagged state a more descriptive label.

'default'
tags list of Tag

Tags to pre-register, in addition to the implicit default_tag_name tag. Tags used for the first time via tag() are auto-registered.

None
initial_status dict, array-like, or None

Restores per-item status for a resumed run (paired with initial), so a bar started mid-way still shows accurate history for the items it didn't itself iterate. Values are raw status ints (as in Tag.status/tag_to_status, not tag names) and must already be registered - via tags - before use here. Accepts: - a dict of {index: status}, for a sparse subset of items; - a 2D array-like of shape (2, N): row 0 is indices, row 1 is the matching statuses, also for a sparse subset; - a 1D array-like of shape (total,), giving every item's status directly (requires total to be known). Defaults to None (every item starts at default_status).

None
reduce_op callable

Reduction applied to the statuses within a bar segment to pick the status (and therefore color) representing that segment (default max, i.e. highest-status tag wins).

max
reduce_ignore_default bool

If True, exclude items still at default_status from the reduction within a segment, unless the whole segment is at default_status (default False).

False
legend bool

If True, print a legend line below the bar showing tag counts (default False).

False
legend_format callable or str

Customizes the legend line. A callable is invoked as legend_format(tag_counts, tag_to_color) -> str for full control. A str is used as a template with a {legend} placeholder for the default swatch rendering (e.g. "tags: {legend}"). Defaults (None) to the built-in colored swatch format, unchanged.

None
legend_show_default bool

If True, include default_tag_name in the legend, with its count derived as processed items minus the sum of all other tag counts (default False, matching the previous behavior of never showing it).

False
prune_legend bool

If True, omit tags with a current count of 0 from the legend (default False, showing every registered tag from the start).

False
**kwargs

Forwarded to tqdm.__init__.

{}

__iter__()

Iterate over the wrapped iterable, resetting each item's status.

Before yielding each item, _current_item_idx is set and its status is reset to default_status, so a fresh item that isn't explicitly tag()-ed still renders with the default color. _current_item_idx is kept as its own counter - distinct from self.n - since it must always be exactly the 0-based position of the item currently being tagged, regardless of self.n's own semantics (which can start at a non-zero initial, be mutated by user code, or lag behind n for display-throttling reasons).

The reset is skipped for a slot that's already been explicitly written (i.e. isn't still _UNSET_STATUS) - which includes a slot deliberately tagged default_status, not just a non-default one. This matters for out-of-order iterables (e.g. concurrent.futures.as_completed), where i is completion order, not the item's true position - the loop body tags the true slot via tag(..., index=true_idx) instead of relying on i. Since i and true_idx are drawn from the same range(total), i will eventually collide with some earlier item's true_idx; without the guard, that coincidence would reset an already-tagged item back to default_status for no reason related to the item at slot i itself.

Drives self.iterable directly and manages self.n via explicit update() calls, rather than delegating to tqdm.__iter__'s generator, so that breaking out of the loop right after tagging the current item still counts it. tqdm.__iter__ only advances n in code positioned after its own yield, which a break skips entirely (Python throws GeneratorExit at the suspended yield); worse, its finally unconditionally does self.n = n, overwriting self.n with that stale, un-incremented count on close - so even wrapping super().__iter__() and patching self.n up afterwards would just get clobbered. Owning the try/finally around our own yield and calling update(1) unconditionally - on normal resumption and on early break alike - avoids that entirely and keeps the just-tagged item's colored segment visible on the final bar.

__iter__old()

Iterate over the wrapped iterable, resetting each item's status.

Before yielding each item, its status is set to default_status so that a fresh item that isn't explicitly tag()-ed still renders with the default color.

Manages self.n via explicit update() calls (rather than delegating to tqdm.__iter__'s generator) so that breaking out of the loop right after tagging the current item still counts it: tqdm.__iter__ only advances n in code positioned after its yield, which a break skips entirely (Python throws GeneratorExit at the suspended yield) - leaving the just-tagged item's colored segment past the render boundary and invisible on the final bar, even though its status was already recorded.

tag(tag, color='none', status=None, index=None)

Record an item's status.

In manual (non-iterable) usage - i.e. no for x in pbar loop driving __iter__ - there's no notion of a "current item" for tag() to target, and nothing that would otherwise advance the bar. tag() falls back to self.n (which, absent an __iter__-driven counter, correctly identifies the item about to complete) and calls update(1) itself, so calling tag() alone both records the status and advances the bar by one - do not also call .update() yourself for that same item, or it will be counted twice.

Parameters:

Name Type Description Default
tag str or Tag

A Tag object or a tag name string referencing a previously defined tag.

required
color str

Override the tag's color for this call. Ignored when "none" (the default sentinel).

'none'
status int

Override the tag's status integer. Only used the first time a new tag name is registered.

None
index int

Item slot to tag, overriding the current item (self.n in manual mode, _current_item_idx while iterating). In manual mode, whether this advances n depends on whether index was ever seen before: a slot still holding _UNSET_STATUS (never written by tag(), initial_status, or __iter__) is treated as a new completion and advances n, exactly like index=None would; a slot that already holds a real status - including default_status, if it was explicitly assigned - is treated as a retry and leaves n alone. This never advances the bar while iterating (self._iterating), since __iter__ already advances n once per pulled item regardless of index. Two uses: - Retrying in manual mode: overwrite a previously tagged item's status (e.g. flip it from "error" to "success" once a retry succeeds) without double-counting it. - Out-of-order completions in manual mode (e.g. iterating concurrent.futures.as_completed directly, not via for x in pbar): the true slot for a completed item has to be looked up (e.g. via a future -> index dict) rather than assumed from completion order; the first tag(..., index=i) for a given i both records its status and counts it.

Caveat: this first-touch detection only sees slots that went through tag() (or initial_status/__iter__). If you count an item with a bare self.update(1) and never call tag(..., index=that_slot) for it, the slot stays _UNSET_STATUS forever - fine on its own, but if you later do call tag(..., index=that_slot) for the first time, it will look unseen and advance n again, double-counting it. Route every completion you intend to also tag() through tag() itself (even the default/success case, e.g. tag(default_tag_name, index=i)) rather than mixing in bare update(1) calls for the same slots.

Works the same whether or not total is known: _set_status pads any gap up to index with _UNSET_STATUS either way - in the preallocated array (total known) it's already filled that way, in the dynamic list (total unknown) it extends the list.

None

format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it', unit_scale=False, rate=None, bar_format=None, postfix=None, unit_divisor=1000, initial=0, colour=None, **extra_kwargs) staticmethod

Return a string-based progress bar given some parameters.

Overrides tqdm.format_meter to render {bar} as a ColoredBar with segments colored by item status.

Parameters:

Name Type Description Default
n int or float

Number of finished iterations.

required
total int or float

Expected total number of iterations. None disables ETA.

required
elapsed float

Seconds elapsed since start.

required
ncols int

Total output width. Dynamically resizes {bar} to fit. 0 prints only stats, no bar.

None
prefix str

Prefix message; available as {desc} in bar_format.

''
ascii bool or str

Use ASCII characters instead of Unicode smooth blocks.

False
unit str

Iteration unit label (default "it").

'it'
unit_scale bool or int or float

If True or 1, apply SI prefixes (k, M, …). Any other non-zero number scales total and n directly.

False
rate float

Manual iteration rate override (default: n / elapsed).

None
bar_format str

Custom bar string. Default: "{l_bar}{bar}{r_bar}" where l_bar = "{desc}: {percentage:3.0f}%|" and r_bar = "| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}{postfix}]". Available placeholders: l_bar, bar, r_bar, n, n_fmt, total, total_fmt, percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, rate, rate_fmt, rate_noinv, rate_noinv_fmt, rate_inv, rate_inv_fmt, postfix, unit_divisor, remaining, remaining_s, eta.

None
postfix str

Additional stats appended after the bar.

None
unit_divisor float

Divisor used when unit_scale is active (default: 1000).

1000
initial int or float

Initial counter value (default: 0).

0
colour str

Bar colour, e.g. "green" or "#00ff00".

None
**extra_kwargs

Forwarded from TqdmTag.format_dict (item_status, status_to_tag, tag_to_color, …).

{}

Returns:

Type Description
str

Formatted meter string ready for display.

display(msg=None, pos=None)

Render the bar, then print the legend line beneath it if enabled.

Overrides tqdm.display. The legend is only written to a TTY (it would corrupt output otherwise) and the cursor is returned to the bar's line afterward so subsequent bar updates overwrite in place.

msg="" is the sentinel tqdm.close (with leave=False) uses to blank the bar's line instead of redrawing it - handled the same way here (blank the legend line rather than redraw it), otherwise a leave=False bar would still leave its legend behind. See _render_legend_line for the shared blank-or-draw logic also used by clear().

Parameters:

Name Type Description Default
msg str

Pre-formatted status message, same as in tqdm.display.

None
pos int

Line offset for multi-bar displays, same as in tqdm.display.

None

clear(nolock=False)

Clear the bar, then blank this bar's legend line too, if drawn.

Overrides tqdm.clear. tqdm.write() clears every live bar (via this method) before printing, then redraws them - without this override, the legend line (drawn outside of tqdm's own line-tracking by display()) would survive that clear, causing the redraw to land one row off and leave a stale legend line behind on every tqdm.write() call.

Parameters:

Name Type Description Default
nolock bool

If True, skip acquiring the internal lock, same as in tqdm.clear (used when the caller already holds it).

False

close()

Close the bar, then move past the legend line if one was drawn.

Overrides tqdm.close.

TqdmErrorTag

Bases: TqdmTag

A TqdmTag with "warn" and "error" tags pre-registered.

Adds convenience warn()/error() methods on top of the generic tag() API. "error" has a higher status than "warn", so with the default reduce_op=max a segment containing both is shown as an error.

__init__(*args, tags=None, **kwargs)

Initialize with the warn/error tags prepended to tags.

Parameters:

Name Type Description Default
*args

Forwarded to TqdmTag.__init__.

()
tags list of Tag

Additional tags to register alongside WARN and ERROR.

None
**kwargs

Forwarded to TqdmTag.__init__.

{}

warn(**kwargs)

Mark the current item with the "warn" tag.

Parameters:

Name Type Description Default
**kwargs

Forwarded to TqdmTag.tag (e.g. color, status overrides).

{}

error(**kwargs)

Mark the current item with the "error" tag.

Parameters:

Name Type Description Default
**kwargs

Forwarded to TqdmTag.tag (e.g. color, status overrides).

{}

ColoredBar

Bases: Bar

Drop-in replacement for tqdm.std.Bar supporting per-segment color.

Behaves like Bar when formatted (supports the same format_spec suffixes a/u/b and numeric width), but colors each rendered block according to segment_colours using ANSI escape codes.

__init__(frac, default_len=10, charset=UTF, segment_colours=None)

Create a bar renderer for the given fraction complete.

Parameters:

Name Type Description Default
frac float

Fraction of the bar that is filled, in [0, 1]. Values outside the range are clamped with a warning.

required
default_len int

Number of segments to render when __format__ isn't given an explicit width (default 10).

10
charset str

String of characters from emptiest to fullest block, used to render partial segments (default UTF).

UTF
segment_colours sequence

Color (name, hex string, or None), or (winner_color, runner_up_color, winner_fraction) for a blended segment, per segment - see TqdmTag._get_colors. Indexed in render order.

None

__format__(format_spec)

Render the bar to a string, coloring each segment.

Supports the same format_spec as tqdm.std.Bar: an optional trailing a/u/b selects the ASCII/UTF/BLANK charset, and a leading integer sets the bar width (negative values subtract from default_len).

A segment whose segment_colours entry is a (winner_color, runner_up_color, winner_fraction) tuple - see TqdmTag._get_colors - renders as a single glyph split proportionally between the two colors (foreground = winner, background = runner-up), using the UTF charset's eighths-block staircase. Only available with the UTF charset; ASCII/BLANK fall back to the winner color alone.

Parameters:

Name Type Description Default
format_spec str

Format specification, e.g. "", "20", "20a", "-5u".

required

Returns:

Type Description
str

The rendered, ANSI-colored bar.