ddp_utils.console.progress

import ddp_utils.console.progress

Render standalone or layout-bound progress bars through DDP Console.

The module owns progress state and line construction but never owns stdout. ProgressConfig records which values were explicitly supplied so a manual fill or empty character can override a named style even when equal to its default value. Styling is delegated to ddp_utils.console.styler.

Examples

Render and complete a progress bar through its context manager:

from ddp_utils.console.progress import ProgressBar

with ProgressBar(total=10, description="Rows") as progress:
    progress.update(10)
ddp_utils.console.progress.get_bar_template(style_name: str | None) → Dict[str, str] | None

Return one predefined bar template by name.

Returns a shallow copy so callers may safely mutate the returned mapping.

Parameters

Name

Type

Description

style_name

str | None

Case-insensitive style name, or None.

Returns

Type

Description

Dict[str, str] | None

Copy of the style mapping, or None for an empty or unknown name.

Examples

Resolve the thin preset without mutating shared defaults:

template = get_bar_template("thin1")
class ddp_utils.console.progress.ProgressConfig(width: Any = UNSET, indent: Any = UNSET, template: Any = UNSET, format_str: Any = UNSET, bar_color: Any = UNSET, empty_color: Any = UNSET, text_color: Any = UNSET, fill_char: Any = UNSET, empty_char: Any = UNSET, bar_style: Any = UNSET, show_time: Any = UNSET, show_percentage: Any = UNSET, show_count: Any = UNSET, persist_on_complete: Any = UNSET, text_over_bar: Any = UNSET, auto_complete: Any = UNSET, compact_format_str: Any = UNSET, auto_compact: Any = UNSET)

Bases: object

Independent configuration for ProgressBar.

This config is standalone and does not depend on ConsoleLogger / LogConfig.

It may be used:

  • directly in ProgressBar(..., config=...);

  • indirectly by ConsoleLogger as a source of defaults.

A plain dataclass cannot distinguish an omitted fill_char from an explicitly supplied value that equals the default.

Here we keep both:

  • the concrete value;

  • the set of explicitly provided fields.

This lets ProgressBar resolve bar_style correctly in cases such as:

ProgressConfig(bar_style="thin1", fill_char="█")

Here "█" equals the default but must still override the named style.

Examples

Override a named style with an explicitly supplied character:

config = ProgressConfig(bar_style="thin1", fill_char="█")

Configure progress rendering while retaining explicit-field intent.

Every omitted argument remains UNSET and receives its class default. Supplied arguments are recorded as explicit, even when their values equal defaults, so merging and named-style resolution preserve caller intent.

Parameters

Name

Type

Description

width

int

Fixed bar width, or zero for automatic sizing.

indent

int

Number of leading spaces.

template

List[Tuple[str, str, str]] | None

Ordered (field, format, color) rendering parts.

format_str

str | None

Placeholder format parsed instead of template.

bar_color

str

Filled-segment color.

empty_color

str

Unfilled-segment color.

text_color

str

Reserved text color setting.

fill_char

str

Character used for completed cells.

empty_char

str

Character used for remaining cells.

bar_style

str | None

Optional predefined character-pair name.

show_time

bool

Include elapsed time in the generated default template.

show_percentage

bool

Include completion percentage.

show_count

bool

Include current/total.

persist_on_complete

bool

Print the final standalone line on completion.

text_over_bar

bool

Retained compatibility setting for render policy.

auto_complete

bool

Complete automatically when progress reaches total.

compact_format_str

str | None

Alternate format used when a line is too wide.

auto_compact

bool

Enable automatic compact-format selection.

Examples

Create an automatically sized compactable configuration:

config = ProgressConfig(
    bar_style="blocks",
    auto_compact=True,
    compact_format_str="{description} {percentage:.0f}%",
)
is_explicit(name: str) → bool

Return True if the field was explicitly provided / overridden.

Parameters

Name

Type

Description

name

str

Configuration field name.

Returns

Type

Description

bool

True when the caller or a merge explicitly assigned the field.

Examples

Check whether a fill character must override a style:

manual_fill = config.is_explicit("fill_char")
copy() → ProgressConfig

Return an independent copy with the same effective configuration.

The copy preserves concrete values and explicit-field metadata. Its mutable template list and explicit-field set are copied rather than shared with the source configuration.

Returns

Type

Description

ProgressConfig

Independent configuration with copied templates and explicit fields.

Examples

Derive settings without mutating the original:

derived = config.copy()
to_kwargs() → Dict[str, Any]

Return config as kwargs payload.

Explicitness metadata is included under a reserved internal key so that merge(**config.to_kwargs()) can preserve “field was explicit” semantics.

Returns

Type

Description

Dict[str, Any]

Constructor-compatible values plus the reserved __explicit_fields__ metadata set.

Examples

Preserve explicitness across a merge round-trip:

payload = config.to_kwargs()
clone = ProgressConfig().merge(**payload)
merge(**overrides) → ProgressConfig

Return a merged config copy.

Merge rules:

  • None values are ignored for backward-compatible behavior;

  • reserved key "__explicit_fields__" may preserve sentinel-aware explicitness across to_kwargs()/merge() roundtrips;

  • absent explicit metadata marks every applied override as explicit.

Parameters

Name

Description

**overrides

Field values and optional __explicit_fields__ metadata. Unknown and None values are ignored.

Returns

Type

Description

ProgressConfig

New merged configuration; the source object is unchanged.

Examples

Override only rendering width and color:

derived = config.merge(width=40, bar_color="cyan")
class ddp_utils.console.progress.ProgressBar(total: int, description: str = 'Progress', width: int | None = None, indent: int | None = None, template: List[Tuple[str, str, str]] | None = None, format_str: str | None = None, bar_color: str | None = None, empty_color: str | None = None, text_color: str | None = None, fill_char: str | None = None, empty_char: str | None = None, bar_style: str | None = None, show_time: bool | None = None, show_percentage: bool | None = None, show_count: bool | None = None, logger=None, console: Console | None = None, layout: ConsoleLayout | None = None, persist_on_complete: bool | None = None, text_over_bar: bool | None = None, auto_complete: bool | None = None, compact_format_str: str | None = None, auto_compact: bool | None = None, on_finish: str = 'keep', config: ProgressConfig | None = None)

Bases: object

Standalone or layout-bound progress bar.

Modes:

  • standalone: register one live renderer in Console footer;

  • layout-bound: register one status renderer in ConsoleLayout.

Examples

Advance a standalone bar and persist its completed line:

progress = ProgressBar(total=100, description="Rows")
progress.update(25)
progress.complete()

Initialize a standalone or layout-bound progress bar.

Priority model:

  1. base ProgressConfig / defaults

  2. bar_style preset pair (fill_char + empty_char)

  3. explicit chars from provided config

  4. explicit chars from constructor kwargs

Parameters

Name

Type

Description

total

int

Total work units; negative values become zero.

description

str

Label rendered before the bar.

width

Optional[int]

Fixed bar width, or None to inherit configuration.

indent

Optional[int]

Leading spaces, or None to inherit configuration.

template

Optional[List[ProgressTemplatePart]]

Explicit ordered render parts.

format_str

Optional[str]

Placeholder format used when no template is supplied.

bar_color

Optional[str]

Filled-cell color override.

empty_color

Optional[str]

Empty-cell color override.

text_color

Optional[str]

Text color compatibility setting.

fill_char

Optional[str]

Manual filled-cell character override.

empty_char

Optional[str]

Manual empty-cell character override.

bar_style

Optional[str]

Predefined character-pair style.

show_time

Optional[bool]

Include elapsed time in the generated template.

show_percentage

Optional[bool]

Include completion percentage.

show_count

Optional[bool]

Include current and total counts.

logger

Optional logger that tracks this active progress object.

console

Optional[Console]

Console used for standalone rendering.

layout

Optional[ConsoleLayout]

Optional layout used for status rendering.

persist_on_complete

Optional[bool]

Print a final standalone line on completion.

text_over_bar

Optional[bool]

Retained compatibility rendering option.

auto_complete

Optional[bool]

Complete automatically at total and on context exit.

compact_format_str

Optional[str]

Alternate narrow-terminal format.

auto_compact

Optional[bool]

Select the compact format when required.

on_finish

str

keep retains the final layout line; remove detaches it after completion or factual finalization.

config

Optional[ProgressConfig]

Base configuration merged with explicit constructor values.

Examples

Create a layout-bound bar using a named character style:

progress = ProgressBar(
    total=50,
    description="Cases",
    layout=layout,
    config=ProgressConfig(bar_style="blocks"),
)
classmethod get_bar_templates() → Dict[str, Dict[str, str]]

Return all predefined bar styles.

Returns

Type

Description

Dict[str, Dict[str, str]]

Detached mapping of style names to fill and empty characters.

Examples

Populate a configuration selector:

styles = ProgressBar.get_bar_templates()
render_line() → str

Render one visible progress line.

Returns

Type

Description

str

ANSI-aware line padded or truncated to the current terminal width.

Examples

Inspect the current visual state without printing it:

line = progress.render_line()
refresh() → None

Register the renderer if needed and request a redraw.

Examples

Refresh after externally changing display state:

progress.refresh()
start() → ProgressBar

Register the progress renderer and return this instance.

Returns

Type

Description

ProgressBar

This active progress bar.

Examples

Start a manually controlled progress bar:

progress = ProgressBar(10).start()
advance(amount: int = 1) → None

Advance progress by amount units.

Parameters

Name

Type

Description

amount

int

Work units to add.

Examples

Advance a manually managed progress bar:

progress.advance(5)
update(advance: int = 1) → None

Advance the progress by advance steps and redraw it.

Important: this method does NOT decide whether the bar should be logically completed. Business code must explicitly call complete() when it wants a forced 100% finalization, or finish() when it wants to keep the factual state.

Parameters

Name

Type

Description

advance

int

Work units to add, capped at total.

Examples

Record a processed batch:

progress.update(advance=25)
set_progress(value: int) → None

Set the current progress value and redraw it.

Important: this method does NOT auto-complete the bar even when value >= total. Final state policy is controlled explicitly by the caller via complete() or finish().

Parameters

Name

Type

Description

value

int

Absolute work count, clamped between zero and total.

Examples

Synchronize with an external counter:

progress.set_progress(75)
complete() → None

Finalize the progress bar as fully completed (100%).

Semantics:

  • force current = total;

  • stop live rendering;

  • optionally persist the final line into history.

Examples

Force a successful final state:

progress.complete()
finish() → None

Finalize the progress bar at its current factual state.

Unlike complete(), this method does NOT force current to total. The current rendered line always remains on screen as-is.

Examples

Preserve a partial final state after early termination:

progress.finish()
close() → None

Detach live renderer without forcing completion.

Examples

Remove a live bar without printing or changing its count:

progress.close()
remove() → None

Remove this progress renderer without changing its value.

Examples

Clear a finished progress row from its group:

progress.remove()
set_description(description: str) → None

Set the progress bar’s description text and re-render.

Parameters

Name

Type

Description

description

str

Replacement display label.

Examples

Identify the current processing stage:

progress.set_description("Downloading")
set_extras(**kwargs) → None

Update one or more registered extra fields and re-render if any value changed.

Parameters

Name

Description

**kwargs

Values for registered extra1 through extra9 fields; unknown keys are ignored and None becomes empty text.

Examples

Update custom filename and status fields:

progress.set_extras(extra1="report.pdf", extra2="verified")
set_extra(key: str, value: Any) → None

Update a single registered extra field.

Parameters

Name

Type

Description

key

str

Registered extra field name.

value

Any

Replacement value converted to text.

Examples

Replace one custom field:

progress.set_extra("extra1", "page 3")
clear_extras() → None

Clear the values of all registered extra fields and re-render.

Examples

Remove stale custom status values:

progress.clear_extras()
set_color(color: str) → None

Set the filled-bar color and re-render.

Parameters

Name

Type

Description

color

str

Color name accepted by the shared styler.

Examples

Highlight successful progress in green:

progress.set_color("green")
set_bar_color(color: str) → None

Alias for set_color().

Parameters

Name

Type

Description

color

str

Filled-segment color passed to set_color().

Examples

Use the explicit alias in configuration code:

progress.set_bar_color("cyan")
set_empty_color(color: str) → None

Set the empty-bar color and re-render.

Parameters

Name

Type

Description

color

str

Empty-segment color accepted by the shared styler.

Examples

Dim remaining cells:

progress.set_empty_color("bright_black")
set_text_color(color: str) → None

Set the label text color and re-render.

Parameters

Name

Type

Description

color

str

Replacement text color compatibility setting.

Examples

Store a white text preference:

progress.set_text_color("white")
set_width(width: int) → None

Set a fixed bar width, adjust layout and re-render.

Parameters

Name

Type

Description

width

int

Fixed cell width; negative values become zero for auto sizing.

Examples

Fix the bar at forty cells:

progress.set_width(40)
set_indent(indent: int) → None

Set the left indent, adjust layout and re-render.

Parameters

Name

Type

Description

indent

int

Leading spaces; negative values become zero.

Examples

Nest a child bar visually:

progress.set_indent(4)
set_template(template: List[Tuple[str, str, str]]) → None

Replace the render template with normalized (part, prefix, suffix) tuples.

Parameters

Name

Type

Description

template

List[Tuple[str, str, str]]

One- through three-item field tuples to normalize.

Raises

Exception

Description

ValueError

A template item has an unsupported length.

Examples

Render only the description and bar:

progress.set_template([("description", "{desc}: "), ("bar", "[{bar}]")])
set_format(format_str: str) → None

Set the bar’s layout from a format string, parsing it into a template.

Parameters

Name

Type

Description

format_str

str

Placeholder format replacing the active template.

Examples

Switch to a concise percentage format:

progress.set_format("{description}: {percentage:.0f}%")
set_fill_char(char: str) → None

Set the character used for the filled portion of the bar, clearing any named bar style.

Parameters

Name

Type

Description

char

str

Non-empty filled-cell text; empty input is ignored.

Examples

Use hash marks and disable the previous named style:

progress.set_fill_char("#")
set_empty_char(char: str) → None

Set the character used for the empty portion of the bar, clearing any named bar style.

Parameters

Name

Type

Description

char

str

Non-empty remaining-cell text; empty input is ignored.

Examples

Use dots for remaining work:

progress.set_empty_char(".")
set_bar_style(style_name: str) → None

Apply a named bar style, deriving fill/empty characters from it.

Parameters

Name

Type

Description

style_name

str

Case-insensitive key from BAR_TEMPLATES.

Raises

Exception

Description

ValueError

The requested style is unknown.

Examples

Apply the predefined blocks pair:

progress.set_bar_style("blocks")
update_with_extras(advance: int = 1, **extras) → None

Advance the bar and update its extra fields in a single call.

Parameters

Name

Type

Description

advance

int

Work units to add.

**extras

Registered extra fields updated before the redraw.

Examples

Advance one file and show its name:

progress.update_with_extras(1, extra1="report.pdf")
configure(config: ProgressConfig | None = None, **kwargs) → None

Reconfigure the progress bar at runtime.

Priority:

  1. base current/provided config

  2. bar_style preset pair

  3. explicit chars from provided/current config

  4. explicit chars from kwargs

Parameters

Name

Type

Description

config

ProgressConfig | None

Replacement base configuration, or the current configuration when omitted.

**kwargs

Runtime field overrides; character overrides have highest style-resolution priority.

Examples

Reconfigure style and width while retaining other state:

progress.configure(bar_style="thin1", width=30)
get_config() → ProgressConfig

Return a copy of the current progress bar configuration.

Returns

Type

Description

ProgressConfig

Independent configuration preserving explicit-field metadata.

Examples

Use current settings as a base for another bar:

config = progress.get_config()