ddp_utils.console.styler¶
import ddp_utils.console.styler
Provide the shared ANSI-compatible and Rich-native styling primitives.
Legacy string APIs and constants remain available while semantic styling is
represented with Rich Style and Text objects internally. The module
does not own streams, cursor state, redraw coordination, or live displays.
Examples
Style one compatibility string and one Rich-native fragment:
from ddp_utils.console.styler import colorize, to_rich_text
legacy = colorize("Ready", color="green")
native = to_rich_text("Ready", color="green")
- ddp_utils.console.styler.strip_ansi(text: str) str¶
Remove ANSI escape sequences from text.
Parameters
Name
Type
Description
text
str
Input converted to a string.
Returns
Type
Description
str
Text without recognized ANSI control sequences.
Examples
Remove styling before visible-width calculations:
plain = strip_ansi("[31mError[0m")
- ddp_utils.console.styler.ansi_fg_code(color: str | None) str¶
Resolve a foreground color to its ANSI code.
Supported inputs:
None
public color name from FG_COLORS
raw ANSI prefix like
[31m
Parameters
Name
Type
Description
color
str | None
Public color name, raw ANSI sequence, or
None.Returns
Type
Description
str
Matching ANSI sequence, or an empty string for unknown input.
Examples
Resolve a named foreground color:
prefix = ansi_fg_code("red")
- ddp_utils.console.styler.ansi_bg_code(bg: str | None) str¶
Resolve a background color to its ANSI code.
Supported inputs:
None
public bg color name from BG_COLORS
raw ANSI prefix like
[41m
Parameters
Name
Type
Description
bg
str | None
Public background name, raw ANSI sequence, or
None.Returns
Type
Description
str
Matching ANSI sequence, or an empty string for unknown input.
Examples
Resolve a named background color:
prefix = ansi_bg_code("blue")
- ddp_utils.console.styler.ansi_style_code(style: Any) str¶
Resolve one or multiple styles to an ANSI prefix.
Supported inputs:
None
single style name
raw ANSI style code
list/tuple/set of style names or ANSI codes
This function remains for backward compatibility. Internally the module now prefers Rich Style objects, but legacy code still imports and uses this API.
Parameters
Name
Type
Description
style
Any
Style name, raw ANSI sequence, collection, or
None.Returns
Type
Description
str
Concatenated recognized ANSI style sequences.
Examples
Combine bold and underline flags:
prefix = ansi_style_code(["bold", "underline"])
- ddp_utils.console.styler.to_rich_style(color: str | None = None, bg: str | None = None, style: Any = None) Style¶
Build a Rich Style from the public ddp_utils.console styling inputs.
Supported inputs are intentionally the same as the legacy ANSI helpers:
color name from
FG_COLORSbackground name from
BG_COLORSstyle name or collection of style names
Conversion rules:
raw ANSI strings are ignored because Rich works with semantic style objects, not with prebuilt ANSI escape sequences;
unknown names are silently ignored to preserve the historical best-effort behavior of the old styler.
Parameters
Name
Type
Description
color
str | None
Semantic foreground name.
bg
str | None
Semantic background name.
style
Any
Style name or collection.
Returns
Type
Description
Style
Rich style containing recognized colors and flags.
Examples
Build a bold green Rich style:
rich_style = to_rich_style(color="green", style="bold")
- ddp_utils.console.styler.to_rich_text(text: Any, color: str | None = None, bg: str | None = None, style: Any = None) Text¶
Convert one text fragment into Rich Text using the package styling contract.
Parameters
Name
Type
Description
text
Any
Source value converted to text.
color
str | None
Foreground color name.
bg
str | None
Background color name.
style
Any
One style or a collection.
Returns
Type
Description
Text
Rich text instance with the resolved semantic style.
Examples
Create a bold warning fragment:
fragment = to_rich_text("Warning", color="yellow", style="bold")
- ddp_utils.console.styler.render_segments_to_rich_text(segments: Sequence[Sequence[Any]], sep: str = '') Text¶
Render a styled segment list into one Rich Text object.
Supported segment forms:
(text,)
(text, color)
(text, color, bg)
(text, color, bg, style)
This is the Rich-native twin of render_segments().
Parameters
Name
Type
Description
segments
Sequence[Sequence[Any]]
Sequence of one- through four-item styled segment records.
sep
str
Plain separator inserted between records.
Returns
Type
Description
Text
Combined Rich text object.
Examples
Combine a label and green state:
text = render_segments_to_rich_text([("State: ",), ("Ready", "green")])
- ddp_utils.console.styler.build_ansi_prefix(color: str | None = None, bg: str | None = None, style: Any = None) str¶
Build one ANSI prefix from public styling inputs.
This helper is intentionally dumb and backward-compatible: it only concatenates our public ANSI style/color/bg codes.
Parameters
Name
Type
Description
color
str | None
Foreground name or ANSI sequence.
bg
str | None
Background name or ANSI sequence.
style
Any
Style name, sequence, or ANSI input.
Returns
Type
Description
str
Concatenated style, foreground, and background prefix.
Examples
Build one bold green prefix:
prefix = build_ansi_prefix(color="green", style="bold")
- ddp_utils.console.styler.apply_base_style_to_ansi(text: Any, color: str | None = None, bg: str | None = None, style: Any = None, reset: bool = True) str¶
Apply a base ANSI style to a string that may contain styled fragments.
Why this helper is needed:
logger-level styles should provide a default for the entire line;
inline fragments produced by
colorize(...)must still override it;after an inline fragment emits
RESET, the base style must be restored.
Parameters
Name
Type
Description
text
Any
Plain or already styled content.
color
str | None
Base foreground color.
bg
str | None
Base background color.
style
Any
Base style name or collection.
reset
bool
Append a final reset when true.
Returns
Type
Description
str
ANSI-capable string with the base prefix restored after inner resets.
Examples
Keep a dim base style around an inline white path:
message = "Saved: " + colorize(path, color="white") line = apply_base_style_to_ansi(message, color="bright_black")
Without this helper, an inner reset would return the remaining text to the terminal default. This helper reapplies the base style after every inner reset.
- ddp_utils.console.styler.rich_text_to_ansi(text: Text) str¶
Render RichText back into an ANSI-capable string.
Needed for style-preserving truncation path.
Parameters
Name
Type
Description
text
Text
Rich text object to render.
Returns
Type
Description
str
ANSI-capable text emitted by an isolated Rich console.
Examples
Preserve Rich styling after truncation:
rendered = rich_text_to_ansi(rich_text)
- ddp_utils.console.styler.truncate_ansi_text(text: Any, max_width: int, overflow: Literal['fold', 'crop', 'ellipsis', 'ignore'] | None = 'ellipsis') str¶
Truncate an ANSI-capable string by visible terminal cell width.
Why this helper exists:
callers in logger/progress/spinner operate on string-based API;
some of those strings may already contain ANSI styling;
plain len(…) is incorrect for terminal rendering;
Rich Text.from_ansi(…) gives correct visible cell accounting.
Parameters
Name
Type
Description
text
Any
Plain or ANSI-capable source.
max_width
int
Maximum visible terminal cells.
overflow
Literal['fold', 'crop', 'ellipsis', 'ignore'] | None
Rich-compatible overflow mode.
Returns
Type
Description
str
Truncated plain text with ANSI removed; callers may reapply styling.
Examples
Fit a styled line into twenty cells:
short = truncate_ansi_text(line, 20, overflow="ellipsis")
- ddp_utils.console.styler.truncate_ansi_preserve_style(text: Any, max_width: int, overflow: Literal['fold', 'crop', 'ellipsis', 'ignore'] | None = 'ellipsis') str¶
Truncate visible terminal width while preserving inline ANSI styling.
Unlike
truncate_ansi_text(), this helper returns ANSI-capable text rather than stripping styling from the result.Parameters
Name
Type
Description
text
Any
Plain or ANSI-capable input.
max_width
int
Maximum visible terminal cells.
overflow
Literal['fold', 'crop', 'ellipsis', 'ignore'] | None
Rich truncation mode.
Returns
Type
Description
str
ANSI-capable truncated text, or empty text for non-positive width.
Examples
Shorten a styled label without discarding its colors:
short = truncate_ansi_preserve_style(label, 20)
- ddp_utils.console.styler.colorize(text: Any, color: str | None = None, bg: str | None = None, style: Any = None, reset: bool = True) str¶
Apply styling to a single text fragment and return an ANSI-capable string.
Historical behavior:
callers expect a ready-to-print string;
most current modules still work with strings rather than Rich Text.
New internal behavior:
try to build Rich Text first when semantic style inputs are provided;
fall back to manual ANSI concatenation when caller passes raw ANSI codes;
keep return type = str for backward compatibility.
Parameters
Name
Type
Description
text
Any
Value converted to text.
color
str | None
Foreground name or raw ANSI sequence.
bg
str | None
Background name or raw ANSI sequence.
style
Any
Style name, collection, or raw ANSI style input.
reset
bool
Append a reset suffix when a prefix is applied.
Returns
Type
Description
str
ANSI-capable styled string, or plain text when no style resolves.
Examples
Create a bold green status:
status = colorize("Ready", color="green", style="bold")
- ddp_utils.console.styler.is_segments_list(value: Any) bool¶
Return True if value looks like a valid styled segment list.
Supported segment forms:
(text,)
(text, color)
(text, color, bg)
(text, color, bg, style)
Parameters
Name
Type
Description
value
Any
Candidate segment collection.
Returns
Type
Description
bool
True only for a list of one- through four-item tuple/list records; an empty list is valid.
Examples
Distinguish a segment payload from ordinary data:
valid = is_segments_list([("State: ",), ("Ready", "green")])
- ddp_utils.console.styler.render_segments(segments: Sequence[Sequence[Any]], sep: str = '', reset: bool = True) str¶
Render a list of styled segments into a single ANSI-capable string.
Parameters
Name
Type
Description
segments
Sequence[Sequence[Any]]
One- through four-item styled segment records.
sep
str
Separator inserted between rendered records.
reset
bool
Reset style after each segment when true.
Returns
Type
Description
str
Combined ANSI-capable string.
Examples
Combine a label with a colored state:
line = render_segments([("State: ",), ("Ready", "green")])
- ddp_utils.console.styler.cprint(arg: Any, color: str | None = None, bg: str | None = None, style: Any = None, reset: bool = True, sep: str = '', end: str = '\n', file=None, flush: bool = True) None¶
Convenience styled print.
If
argis a segments list, render it via render_segments(). Otherwise style a single text value via colorize().This function intentionally stays thin:
it does not coordinate terminal state;
full output coordination belongs to Console.
Parameters
Name
Type
Description
arg
Any
Scalar value or valid styled segment list.
color
str | None
Foreground color for scalar input.
bg
str | None
Background color for scalar input.
style
Any
Style or styles for scalar input.
reset
bool
Reset applied styles when true.
sep
str
Separator for a segment list.
end
str
Text appended after rendered content.
file
Destination stream, defaulting to
sys.stdout.flush
bool
Flush the destination after writing.
Examples
Print a green completion message:
cprint("Complete", color="green")