progressbar.widgets module

Widget implementations for progress bars.

A widget is a callable rendering one segment of a bar’s line. See WidgetBase (fixed-width) and AutoWidthWidgetBase (stretches to fill the remaining space) for the call protocol every widget implements.

class progressbar.widgets.AbsoluteETA(format_not_started='Estimated finish time:  ----/--/-- --:--:--', format_finished='Finished at: %(elapsed)s', format='Estimated finish time: %(eta)s', **kwargs)[source]

Bases: ETA

Widget which attempts to estimate the absolute time of arrival.

Create an AbsoluteETA with clock-time-flavoured defaults.

class progressbar.widgets.AdaptiveETA(exponential_smoothing=True, exponential_smoothing_factor=0.1, **kwargs)[source]

Bases: ETA, SamplesMixin

WidgetBase which attempts to estimate the time of arrival.

Uses a sampled average of the speed based on the 10 last updates. Very convenient for resuming the progress halfway. For an estimate based on an exponential moving average (EMA) of the speed instead of a windowed sample, use SmoothingETA.

Store exponential-smoothing config.

Parameters:
  • exponential_smoothing – Accepted for backward compatibility; not read by AdaptiveETA.__call__, which always averages over the sampled window (see SamplesMixin). Use SmoothingETA for an actual EMA-based estimate.

  • exponential_smoothing_factor – Same caveat as exponential_smoothing.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

exponential_smoothing: bool
exponential_smoothing_factor: float
class progressbar.widgets.AdaptiveTransferSpeed(**kwargs: Any)[source]

Bases: FileTransferSpeed, SamplesMixin

Widget for showing the transfer speed based on the last X samples.

Create an AdaptiveTransferSpeed (see FileTransferSpeed).

class progressbar.widgets.AnimatedMarker(markers: str = '|/-\\', default: str | None = None, fill: str = '', marker_wrap: str | tuple[str | None, str | None] | None = None, fill_wrap: str | tuple[str | None, str | None] | None = None, **kwargs: Any)[source]

Bases: TimeSensitiveWidgetBase

An animated marker that defaults to appearing as if it were rotating.

Create an AnimatedMarker.

Parameters:
  • markers – Sequence of single-character frames cycled through on every redraw.

  • default – Frame shown once finished when fill is unset; defaults to markers[0].

  • fill – Marker character/callable used to pad the frame to width (see create_marker). Unset means no filling.

  • marker_wrap – Begin/end strings or template wrapped around the marker frame (see create_wrapper).

  • fill_wrap – Same as marker_wrap, for the fill.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.widgets.AutoWidthWidgetBase(*args: Any, fixed_colors=None, gradient_colors=None, **kwargs: Any)[source]

Bases: WidgetBase

The base class for all variable width widgets.

This widget is much like the hfill command in TeX, it will expand to fill the line. You can use more than one in the same line, and they will all have the same width, and together will fill the line.

Called as widget(progress, data, width), receiving the exact pixel budget it must fill (see WidgetBase.__call__ for the fixed-width counterpart). It must pad or truncate its own output to exactly width.

Apply optional per-instance color overrides.

Parameters:
  • fixed_colors – Partial override of _fixed_colors (e.g. just fg_none).

  • gradient_colors – Partial override of _gradient_colors.

  • *args – Forwarded to the next class in the cooperative __init__ chain.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

Both overrides are merged on top of the class-level default into a fresh per-instance dict rather than mutating it in place, so one instance’s fixed_colors/gradient_colors never leaks into another instance or subclass sharing the same class default. Any cached uses_colors is also dropped, so a cooperative __init__ chain that applies colors on a later pass than the one that first computed uses_colors doesn’t keep a stale uses_colors=False from before the colors were applied.

class progressbar.widgets.Bar(marker='#', left='|', right='|', fill=' ', fill_left=True, marker_wrap=None, **kwargs)[source]

Bases: AutoWidthWidgetBase

A progress bar which stretches to fill the line.

Create the bar with its marker and border characters.

Parameters:
  • marker – Character, or (progress, data, width) -> str callable, used for the filled portion.

  • left – Character, or callable, used as the left border.

  • right – Character, or callable, used as the right border.

  • fill – Character used for the empty part of the bar.

  • fill_left – Fill/grow from the left. If False, from the right.

  • marker_wrap – Begin/end strings or template wrapped around a string marker (see create_wrapper). Ignored for a callable marker.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.widgets.BouncingBar(marker='#', left='|', right='|', fill=' ', fill_left=True, marker_wrap=None, **kwargs)[source]

Bases: Bar, TimeSensitiveWidgetBase

A bar which has a marker which bounces from side to side.

Create the bar with its marker and border characters.

Parameters:
  • marker – Character, or (progress, data, width) -> str callable, used for the filled portion.

  • left – Character, or callable, used as the left border.

  • right – Character, or callable, used as the right border.

  • fill – Character used for the empty part of the bar.

  • fill_left – Fill/grow from the left. If False, from the right.

  • marker_wrap – Begin/end strings or template wrapped around a string marker (see create_wrapper). Ignored for a callable marker.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

INTERVAL = datetime.timedelta(microseconds=100000)
class progressbar.widgets.ColoredMixin[source]

Bases: object

Yellow/gradient color defaults for Percentage/SimpleProgress.

class progressbar.widgets.Counter(format='%(value)d', **kwargs: Any)[source]

Bases: FormatWidgetMixin, WidgetBase

Displays the current count.

Create a Counter with the given format string.

class progressbar.widgets.CurrentTime(format='Current Time: %(current_time)s', microseconds=False, **kwargs)[source]

Bases: FormatWidgetMixin, TimeSensitiveWidgetBase

Widget which displays the current (date)time with seconds resolution.

Create a CurrentTime.

Parameters:
  • format – Template string. Adds current_time/ current_datetime keys on top of the usual data() set.

  • microseconds – Keep microsecond resolution instead of truncating to whole seconds.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

INTERVAL = datetime.timedelta(seconds=1)
current_datetime()[source]

Return datetime.now(), seconds-truncated unless microseconds.

current_time()[source]

Return self.current_datetime()’s time-of-day component.

class progressbar.widgets.DataSize(variable='value', format='%(scaled)5.1f %(prefix)s%(unit)s', unit='B', prefixes=('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'), **kwargs)[source]

Bases: FormatWidgetMixin, WidgetBase

Widget for showing an amount of data transferred/processed.

Automatically formats the value (assumed to be a count of bytes) with an appropriate sized unit, based on the IEC binary prefixes (powers of 1024).

Create a DataSize.

Parameters:
  • variable – Key in data holding the byte count to render.

  • format – The template string (see FormatWidgetMixin).

  • unit – Unit label appended after the IEC prefix.

  • prefixes – IEC binary prefixes, smallest (none) to largest.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.widgets.DynamicMessage(name, format='{name}: {formatted_value}', width=6, precision=3, **kwargs)[source]

Bases: Variable

Legacy alias for Variable. Prefer Variable in new code.

Kept as a plain subclass (no DeprecationWarning) until the next major version.

Create a Variable rendering the bar variable name.

Parameters:
  • namedata[‘variables’] key to read (see VariableMixin).

  • formatstr.format() template. Besides the usual keys it gets name, value, width, precision, and formatted_value (value formatted per width/ precision if numeric, else ‘-’ * width if falsy).

  • width – Minimum field width used to format a numeric value.

  • precision – Decimal precision used to format a numeric value.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.widgets.ETA(format_not_started='ETA:  --:--:--', format_finished='Time: %(elapsed)8s', format='ETA:  %(eta)8s', format_zero='ETA:  00:00:00', format_na='ETA:      N/A', **kwargs)[source]

Bases: Timer

WidgetBase which attempts to estimate the time of arrival.

Create an ETA, rewriting a legacy bare %s placeholder.

Parameters:
  • format_not_started – Format used before any progress has been made (value == min_value).

  • format_finished – Format used once the bar has finished.

  • format – Format used once an ETA is available.

  • format_zero – Format used when elapsed time is exactly zero.

  • format_na – Format used when no ETA can be computed (unknown max_value).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

Rewrites a legacy bare %s placeholder to the named %(eta)s form (see Timer.__init__ for the same elapsed-time shim).

class progressbar.widgets.FileTransferSpeed(format='%(scaled)5.1f %(prefix)s%(unit)-s/s', inverse_format='%(scaled)5.1f s/%(prefix)s%(unit)-s', unit='B', prefixes=('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'), **kwargs)[source]

Bases: FormatWidgetMixin, TimeSensitiveWidgetBase

Widget showing the transfer speed (useful for file transfers).

Create a FileTransferSpeed.

Parameters:
  • format – Template used once a speed can be computed.

  • inverse_format – Template used for slow transfers (see __call__), rendering seconds-per-unit instead of units-per-second.

  • unit – Unit label appended after the IEC prefix.

  • prefixes – IEC binary prefixes, smallest (none) to largest.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.widgets.FormatCustomText(format: str, mapping: dict[str, Any] | None = None, **kwargs)[source]

Bases: FormatWidgetMixin, WidgetBase

A widget that formats its own mapping instead of data().

Not driven by the bar’s progress at all: update_mapping lets calling code push arbitrary key/value pairs to render, so this acts as a free-form status line alongside the bar. copy = False because its whole point is shared, externally-updated state, unlike ordinary widgets (see WidgetBase’s copy note).

Create a FormatCustomText.

Parameters:
  • format – The template string. Keys come from self.mapping, not the bar’s data().

  • mapping – Initial mapping. Defaults to a copy of the class- level mapping (empty unless a subclass overrides it).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

copy = False
mapping: dict[str, Any] = {}
update_mapping(**mapping: Any)[source]

Merge mapping into self.mapping for the next render.

class progressbar.widgets.FormatLabel(format: str, **kwargs: Any)[source]

Bases: FormatWidgetMixin, WidgetBase

Displays a formatted label.

>>> label = FormatLabel('%(value)s', min_width=5, max_width=10)
>>> class Progress:
...     pass
>>> label = FormatLabel('{value} :: {value:^6}', new_style=True)
>>> str(label(Progress, dict(value='test')))
'test ::  test '

Create a FormatLabel for the given format string.

mapping: ClassVar[dict[str, tuple[str, Any]]] = {'elapsed': ('total_seconds_elapsed', <function format_time>), 'finished': ('end_time', None), 'last_update': ('last_update_time', None), 'max': ('max_value', None), 'seconds': ('seconds_elapsed', None), 'start': ('start_time', None), 'value': ('value', None)}
class progressbar.widgets.FormatLabelBar(format, **kwargs: Any)[source]

Bases: FormatLabel, Bar

A bar which has a formatted label in the center.

Create a FormatLabelBar with the given format string.

Parameters:
  • format – The label template (see FormatLabel).

  • **kwargs – Forwarded to Bar.__init__.

class progressbar.widgets.FormatWidgetMixin(format: str, new_style: bool = False, **kwargs: Any)[source]

Bases: object

Mixin to format widgets using a %- or str.format-style string.

data() is the authoritative definition of the keys a format= string can reference (value, max_value, percentage, the elapsed-time fields, and so on).

Store the format string.

Parameters:
  • format – The template to render with, %-style unless new_style is set.

  • new_style – Use str.format() semantics instead of %.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

get_format(progress: ProgressBarMixinBase, data: Data, format: str | None = None) str[source]

Return the format string to render with, default self.format.

class progressbar.widgets.GranularBar(markers=' ▏▎▍▌▋▊▉█', left='|', right='|', **kwargs)[source]

Bases: AutoWidthWidgetBase

A progressbar with sub-character granularity via multiple markers.

Examples of markers:
  • Smooth: ` ▏▎▍▌▋▊▉█` (default)

  • Bar: ` ▁▂▃▄▅▆▇█`

  • Snake: ` ▖▌▛█`

  • Fade in: ` ░▒▓█`

  • Dots: ` ⡀⡄⡆⡇⣇⣧⣷⣿`

  • Growing circles: ` .oO`

The markers can be accessed through GranularMarkers. GranularMarkers.dots for example

Create a GranularBar with its marker ramp and borders.

Parameters:
  • markers – String of characters to use as granular progress markers. The first character should represent 0% and the last 100%. Ex: ` .oO`.

  • left – String or callable object to use as a left border.

  • right – String or callable object to use as a right border.

  • **kwargs – Forwarded to AutoWidthWidgetBase.__init__.

class progressbar.widgets.GranularMarkers[source]

Bases: object

Preset marker strings for GranularBar, sparsest to fullest.

bar = ' ▁▂▃▄▅▆▇█'
dots = ' ⡀⡄⡆⡇⣇⣧⣷⣿'
fade_in = ' ░▒▓█'
growing_circles = ' .oO'
smooth = ' ▏▎▍▌▋▊▉█'
snake = ' ▖▌▛█'
class progressbar.widgets.JobStatusBar(name: str, left='|', right='|', fill=' ', fill_left=True, success_fg_color=((0, 128, 0), (120, 100, 25), 'Green', 2), success_bg_color=None, success_marker='█', failure_fg_color=((255, 0, 0), (0, 100, 50), 'Red', 9), failure_bg_color=None, failure_marker='X', **kwargs)[source]

Bases: Bar, VariableMixin

Widget which displays the job status as markers on the bar.

The status updates can be given either as a boolean or as a string. If it’s a string, it will be displayed as-is. If it’s a boolean, it will be displayed as a marker (default: ‘█’ for success, ‘X’ for failure) configurable through the success_marker and failure_marker parameters. See __init__ for the full parameter list.

Create a JobStatusBar.

Parameters:
  • namedata[‘variables’] key holding each status update.

  • left – The left border of the bar.

  • right – The right border of the bar.

  • fill – The fill character of the bar.

  • fill_left – Whether to fill the bar from the left or the right.

  • success_fg_color – Foreground color for successful jobs.

  • success_bg_color – Background color for successful jobs.

  • success_marker – Marker character for successful jobs.

  • failure_fg_color – Foreground color for failed jobs.

  • failure_bg_color – Background color for failed jobs.

  • failure_marker – Marker character for failed jobs.

  • **kwargs – Forwarded to Bar.__init__.

failure_bg_color: Color | None = None
failure_fg_color: Color | None = ((255, 0, 0), (0, 100, 50), 'Red', 9)
failure_marker: str = 'X'
get_job_markers(progress: ProgressBarMixinBase) list[str][source]

Return this bar’s colored marker history, creating it if needed.

Per-bar marker history, following SamplesMixin’s progress.extra pattern so the widget itself stays stateless; see SamplesMixin.get_sample_times for why that matters.

job_markers: list[str]

Unused, retained for backwards compatibility only.

Per-run marker state lives in progress.extra instead (see get_job_markers()).

success_bg_color: Color | None = None
success_fg_color: Color | None = ((0, 128, 0), (120, 100, 25), 'Green', 2)
success_marker: str = '█'
class progressbar.widgets.MultiProgressBar(name, markers=' ▁▂▃▄▅▆▇█', **kwargs)[source]

Bases: MultiRangeBar

A bar summarising many sub-progresses as a per-marker histogram.

data[‘variables’][name] holds one entry per sub-progress, each either a 0..1 fraction or a (value, max) pair. get_values buckets them into len(markers) histogram slots (see its docstring for the bucketing rule).

Create a MultiProgressBar.

Parameters:
  • namedata[‘variables’] key holding the sub-progress list (see the class docstring).

  • markers – Ascending-height marker characters, sparsest (0%) to fullest (100%). Reversed internally to match MultiRangeBar’s marker order.

  • **kwargs – Forwarded to MultiRangeBar.__init__.

get_values(progress: ProgressBarMixinBase, data: Data)[source]

Bucket each sub-progress fraction into the marker histogram.

Each value maps to a position along len(markers) - 1 slots; since that position is usually fractional, it spills across its two neighbouring slots weighted by how close it lands to each (e.g. a value 30% of the way from slot 2 to slot 3 adds 0.7 to slot 2’s count and 0.3 to slot 3’s), so the histogram reflects fractional progress rather than rounding every value to its nearest marker.

class progressbar.widgets.MultiRangeBar(name, markers, **kwargs: Any)[source]

Bases: Bar, VariableMixin

A bar with multiple sub-ranges, each represented by a different symbol.

The various ranges are represented on a user-defined variable, formatted as

[['Symbol1', amount1], ['Symbol2', amount2], ...]

Create a MultiRangeBar.

Parameters:
  • namedata[‘variables’] key holding the range amounts (see VariableMixin).

  • markers – One single-character marker (or callable, see string_or_lambda) per range, in the same order as the amounts in data[‘variables’][name].

  • **kwargs – Forwarded to Bar.__init__.

get_values(progress: ProgressBarMixinBase, data: Data)[source]

Return the configured [amount, …] list, or [] if unset.

class progressbar.widgets.Percentage(format='%(percentage)3d%%', na='N/A%%', **kwargs: Any)[source]

Bases: FormatWidgetMixin, ColoredMixin, WidgetBase

Displays the current percentage as a number with a percent sign.

Create a Percentage.

Parameters:
  • format – Template used once a percentage is available.

  • na – Template used when it isn’t (data[‘percentage’] is None).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

get_format(progress: ProgressBarMixinBase, data: Data, format=None)[source]

Return self.na, colored, when no percentage is available yet.

class progressbar.widgets.PercentageLabelBar(format='%(percentage)2d%%', na='N/A%%', **kwargs: Any)[source]

Bases: Percentage, FormatLabelBar

A bar which displays the current percentage in the center.

Create a PercentageLabelBar.

Parameters:
  • format – The percentage template (see Percentage). Uses %2d rather than Percentage’s default %3d, which adds a padding space that looks off-centre here.

  • na – Template used when no percentage is available.

  • **kwargs – Forwarded to FormatLabelBar.__init__.

class progressbar.widgets.Postfix(name='postfix', prefix=' ', separator=', ', **kwargs: Any)[source]

Bases: VariableMixin, WidgetBase

Displays a live postfix string or key-value mapping.

Create a Postfix.

Parameters:
  • namedata[‘variables’] key to read (see VariableMixin).

  • prefix – Prepended to the rendered value. Empty when the value itself is falsy (nothing to show).

  • separator – Joins key=value pairs when the variable holds a dict.

  • **kwargs – Forwarded to WidgetBase.__init__.

class progressbar.widgets.ReverseBar(marker='#', left='|', right='|', fill=' ', fill_left=False, **kwargs)[source]

Bases: Bar

A bar which has a marker that goes from right to left.

Create a Bar that fills from the right by default.

See Bar.__init__ for parameter meaning. fill_left defaults to False here instead of True.

progressbar.widgets.RotatingMarker

alias of AnimatedMarker

class progressbar.widgets.SamplesMixin(samples: timedelta | int = datetime.timedelta(seconds=2), key_prefix=None, **kwargs)[source]

Bases: TimeSensitiveWidgetBase

Mixin for widgets that average multiple measurements.

samples can be either an integer sample count or a timedelta window.

>>> class progress:
...     last_update_time = datetime.datetime.now()
...     value = 1
...     extra = dict()
>>> samples = SamplesMixin(samples=2)
>>> samples(progress, None, True)
(None, None)
>>> progress.last_update_time += datetime.timedelta(seconds=1)
>>> samples(progress, None, True) == (datetime.timedelta(seconds=1), 0)
True
>>> progress.last_update_time += datetime.timedelta(seconds=1)
>>> samples(progress, None, True) == (datetime.timedelta(seconds=1), 0)
True
>>> samples = SamplesMixin(samples=datetime.timedelta(seconds=1))
>>> _, value = samples(progress, None)
>>> value
SliceableDeque([1, 1])
>>> samples(progress, None, True) == (datetime.timedelta(seconds=1), 0)
True

Configure the sample window.

Parameters:
  • samples – Either a max sample count, or a timedelta window measured back from the most recent sample.

  • key_prefix – Prefix for the progress.extra keys the sample deques are stored under. Defaults to the class name so sibling widget classes on the same bar don’t collide.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

get_sample_times(progress: ProgressBarMixinBase, data: Data)[source]

Return this bar’s sample-time deque, creating it if needed.

Stored on progress.extra (keyed by self.key_prefix), not on self, which keeps the widget stateless: the history belongs to the bar, so ProgressBar.init() clears it when a bar is restarted, and a widget instance that does end up shared between bars cannot mix their samples together. Widgets passed via widgets= are deep-copied per bar by ProgressBar._copy_widgets, so sharing is the exception rather than the rule.

get_sample_values(progress: ProgressBarMixinBase, data: Data)[source]

Return this bar’s sample-value deque, creating it if needed.

See get_sample_times for why this lives on progress.extra.

class progressbar.widgets.SimpleProgress(format='%(value_s)s of %(max_value_s)s', **kwargs: Any)[source]

Bases: FormatWidgetMixin, ColoredMixin, WidgetBase

Returns progress as a count of the total (e.g.: “5 of 47”).

Create a SimpleProgress with the given format string.

DEFAULT_FORMAT = '%(value_s)s of %(max_value_s)s'
max_width_cache: dict[str | tuple[NumberT | type[base.UnknownLength] | None, NumberT | type[base.UnknownLength] | None], int | None]
class progressbar.widgets.SmoothingETA(smoothing_algorithm: type[SmoothingAlgorithm] = <class 'progressbar.algorithms.ExponentialMovingAverage'>, smoothing_parameters: dict[str, float] | None=None, **kwargs)[source]

Bases: ETA

WidgetBase which estimates the ETA from an exponential moving average.

EMA applies more weight to recent data points and less to older ones, and doesn’t require storing all past values. This approach works well with varying data points and smooths out fluctuations effectively.

Instantiate the smoothing algorithm.

Parameters:
  • smoothing_algorithmSmoothingAlgorithm subclass to instantiate. Defaults to ExponentialMovingAverage.

  • smoothing_parameters – Keyword arguments passed to smoothing_algorithm’s constructor.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

smoothing_algorithm: SmoothingAlgorithm
smoothing_parameters: dict[str, float]
class progressbar.widgets.TFixedColors[source]

Bases: TypedDict

Shape of WidgetBase._fixed_colors: colors with no percentage.

bg_none: Color | None
fg_none: Color | None
class progressbar.widgets.TGradientColors[source]

Bases: TypedDict

Shape of WidgetBase._gradient_colors: colors by percentage.

bg: Color | ColorGradient | None
fg: Color | ColorGradient | None
class progressbar.widgets.TimeSensitiveWidgetBase(*args: Any, fixed_colors=None, gradient_colors=None, **kwargs: Any)[source]

Bases: WidgetBase

The base class for all time sensitive widgets.

Some widgets like timers would become out of date unless updated at least every INTERVAL

Apply optional per-instance color overrides.

Parameters:
  • fixed_colors – Partial override of _fixed_colors (e.g. just fg_none).

  • gradient_colors – Partial override of _gradient_colors.

  • *args – Forwarded to the next class in the cooperative __init__ chain.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

Both overrides are merged on top of the class-level default into a fresh per-instance dict rather than mutating it in place, so one instance’s fixed_colors/gradient_colors never leaks into another instance or subclass sharing the same class default. Any cached uses_colors is also dropped, so a cooperative __init__ chain that applies colors on a later pass than the one that first computed uses_colors doesn’t keep a stale uses_colors=False from before the colors were applied.

INTERVAL = datetime.timedelta(microseconds=100000)
class progressbar.widgets.Timer(format='Elapsed Time: %(elapsed)s', **kwargs: Any)[source]

Bases: FormatLabel, TimeSensitiveWidgetBase

WidgetBase which displays the elapsed seconds.

Create a Timer, rewriting a legacy bare %s placeholder.

Very old configs used a bare %s placeholder for the elapsed time. It is silently rewritten here to the named %(elapsed)s form this widget actually formats with.

static format_time(timestamp: timedelta | date | datetime | str | int | float | None, precision: timedelta = datetime.timedelta(seconds=1)) str

Formats timedelta/datetime/seconds.

>>> format_time('1')
'0:00:01'
>>> format_time(1.234)
'0:00:01'
>>> format_time(1)
'0:00:01'
>>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> format_time(datetime.date(2000, 1, 2))
'2000-01-02'
>>> format_time(datetime.timedelta(seconds=3661))
'1:01:01'
>>> format_time(None)
'--:--:--'
>>> format_time(format_time)
Traceback (most recent call last):
    ...
TypeError: Unknown type ...
class progressbar.widgets.UnitProgress(unit=<object object>, unit_scale=<object object>, **kwargs: Any)[source]

Bases: WidgetBase

Displays progress as a count with an optional unit and 1024 scaling.

Create a UnitProgress.

Parameters:
  • unit – Unit label. Defaults to following data[‘unit’] (the bar’s own unit=) rather than a fixed value.

  • unit_scale – Whether to IEC-scale the count. Defaults to following data[‘unit_scale’].

  • **kwargs – Forwarded to WidgetBase.__init__.

unit: str
unit_scale: bool
class progressbar.widgets.Variable(name, format='{name}: {formatted_value}', width=6, precision=3, **kwargs)[source]

Bases: FormatWidgetMixin, VariableMixin, WidgetBase

Displays a custom variable.

Create a Variable rendering the bar variable name.

Parameters:
  • namedata[‘variables’] key to read (see VariableMixin).

  • formatstr.format() template. Besides the usual keys it gets name, value, width, precision, and formatted_value (value formatted per width/ precision if numeric, else ‘-’ * width if falsy).

  • width – Minimum field width used to format a numeric value.

  • precision – Decimal precision used to format a numeric value.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

class progressbar.widgets.VariableMixin(name, **kwargs: Any)[source]

Bases: _WidgetKwargsSink

Mixin to display a custom user variable.

Store the data[‘variables’] key this widget reads.

Parameters:
  • name – A single word, used to look up the value in data[‘variables’]/bar.update(name=value).

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

Raises:
class progressbar.widgets.WidgetBase(*args: Any, fixed_colors=None, gradient_colors=None, **kwargs: Any)[source]

Bases: WidthWidgetMixin

The base class for all widgets.

The ProgressBar will call the widget’s update value when the widget should be updated. The widget’s size may change between calls, but the widget may display incorrectly if the size changes drastically and repeatedly.

The INTERVAL timedelta informs the ProgressBar that it should be updated more often because it is time sensitive.

The widgets are only visible if the screen is within a specified size range so the progressbar fits on both large and small screens.

State specific to one progressbar belongs in progress.extra (see e.g. SamplesMixin) rather than on the widget, which keeps the widget stateless: the bar owns the state and clears it on restart. Widgets passed via widgets= are deep-copied per bar by ProgressBar._copy_widgets unless they set copy = False, so a genuinely shared instance is the exception – but a widget that keeps per-bar state on itself breaks in exactly that case.

Variables available:
  • min_width: Only display the widget if at least min_width is left

  • max_width: Only display the widget if at most max_width is left

  • weight: Widgets with a higher weight will be calculated before widgets with a lower one

  • copy: Copy this widget when initializing the progress bar so the progressbar can be reused. Some widgets such as the FormatCustomText require the shared state so this needs to be optional

Apply optional per-instance color overrides.

Parameters:
  • fixed_colors – Partial override of _fixed_colors (e.g. just fg_none).

  • gradient_colors – Partial override of _gradient_colors.

  • *args – Forwarded to the next class in the cooperative __init__ chain.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

Both overrides are merged on top of the class-level default into a fresh per-instance dict rather than mutating it in place, so one instance’s fixed_colors/gradient_colors never leaks into another instance or subclass sharing the same class default. Any cached uses_colors is also dropped, so a cooperative __init__ chain that applies colors on a later pass than the one that first computed uses_colors doesn’t keep a stale uses_colors=False from before the colors were applied.

copy = True
property uses_colors

Return whether any fixed or gradient color is configured.

class progressbar.widgets.WidthWidgetMixin(min_width: int | None = None, max_width: int | None = None, **kwargs: Any)[source]

Bases: _WidgetKwargsSink

Hide the widget outside a configured terminal-width range.

So a progress bar can carry extra decoration that only fits on wide terminals without breaking narrow ones.

Variables available:
  • min_width: Only display the widget if at least min_width is left

  • max_width: Only display the widget if at most max_width is left

>>> class Progress:
...     term_width = 0
>>> WidthWidgetMixin(5, 10).check_size(Progress)
False
>>> Progress.term_width = 5
>>> WidthWidgetMixin(5, 10).check_size(Progress)
True
>>> Progress.term_width = 10
>>> WidthWidgetMixin(5, 10).check_size(Progress)
True
>>> Progress.term_width = 11
>>> WidthWidgetMixin(5, 10).check_size(Progress)
False

Store the width bounds check_size gates on.

Parameters:
  • min_width – Hide the widget when the terminal is narrower than this.

  • max_width – Hide the widget when the terminal is wider than this.

  • **kwargs – Forwarded to the next class in the cooperative __init__ chain.

check_size(progress: ProgressBarMixinBase) bool[source]

Return whether the widget fits at the current terminal width.

progressbar.widgets.create_marker(marker: str | Callable[[...], str], wrap: str | tuple[str | None, str | None] | None = None) Callable[[...], str][source]

Build a marker-rendering callable from a character or callable.

A single-character marker string becomes a callable that repeats it proportionally to where progress.value sits between progress.min_value and progress.max_value, clamped to width. A callable marker is used as-is. Either way, the result is passed through wrapper() so wrap still applies.

Raises:

ValueErrormarker is a string that isn’t exactly one character.

progressbar.widgets.create_wrapper(wrapper: str | tuple[str | None, str | None] | None) str | None[source]

Convert a wrapper tuple or format string to a format string.

>>> create_wrapper('')
>>> print(create_wrapper('a{}b'))
a{}b
>>> print(create_wrapper(('a', 'b')))
a{}b
progressbar.widgets.format_unit_value(value: NumberT | type[base.UnknownLength] | None, unit: str = 'it', unit_scale: bool = False) str[source]

Render a count with its unit, optionally IEC-scaled.

Parameters:
  • value – The count to render. None or UnknownLength renders as ‘N/A’.

  • unit – Unit label appended after the value (and IEC prefix, if unit_scale).

  • unit_scale – Scale value by IEC binary prefixes (Ki, Mi, …) instead of rendering the raw count.

progressbar.widgets.string_or_lambda(input_: str | Callable[[...], str]) Callable[[...], str][source]

Turn a %-format string into a (progress, data, width) renderer.

A callable input_ is returned unchanged.

progressbar.widgets.wrapper(function, wrapper_)[source]

Wrap function’s return value using wrapper_.

wrapper_ is resolved through create_wrapper(). If that yields None (no wrapping configured), function is returned unchanged.