API Reference
Robust API reference for the console package.
Printer¶
Color-aware, nest-friendly pretty printer for Python structures.
Features¶
- Dicts: inline scalars (
key: value), nested values expand with indentation. - Lists/Tuples/Sets: index/marker labels, nested values expand.
- Optional ANSI color (auto disabled when the stream is not a TTY).
- Optional type hints (
(str),(int), ...). - String truncation for long values.
Notes¶
The color palette is loaded from ansi_colors.json which is ensured on first
use via :func:sciwork.console.create_ansi_colors_config. The default location is
<cwd>/sciwork/configs/ansi_colors.json; switch to the user location by
calling :class:Printer with prefer='user'.
Source code in src/sciwork/console/printer.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
__enter__()
¶
Enter context.
Saves actual "user-adjustable" states so that they are renewed by exit. Attributes are changeable within the block: with printer as p: p._use_color_flag = False p.printer(obj)
Source code in src/sciwork/console/printer.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
__exit__(exc_type, exc_val, exc_tb)
¶
Exit context: renews the state before entering the block.
Returns:
| Type | Description |
|---|---|
bool
|
False. |
Source code in src/sciwork/console/printer.py
84 85 86 87 88 89 90 91 92 93 94 95 96 | |
__repr__()
¶
Unambiguous representation of printer.
Source code in src/sciwork/console/printer.py
57 58 59 60 61 | |
__str__()
¶
Concise representation of printer.
Source code in src/sciwork/console/printer.py
63 64 65 66 | |
printer(obj, indent=0, sort_keys=True, show_types=False, max_str=200, stream=sys.stdout)
¶
Pretty-prints nested Python structures (dict, list, tuple, set, etc.) with inline keys/indices on the same line. Supports optional color, type hints, sorting of dict keys, and string truncation for readability.
Behavior¶
- Dicts: 'key: value' on a single line when value is scalar; nested values expand with indentation.
- Lists: '[idx]: value' on a single line when scalar; nested values expand.
- Tuples: '(idx): value' labels.
- Sets: '{•}: value' labels (order not guaranteed; sorted when possible).
- Scalars: printed directly; long strings are truncated to 'max_str' characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Object to be printed. |
required |
indent
|
int
|
Current indentation level (internal for recursion). |
0
|
sort_keys
|
bool
|
Sort dictionary keys alphabetically (safe if keys are comparable). |
True
|
show_types
|
bool
|
Append the value's type in a dim style, e.g., '(str)'. |
False
|
max_str
|
Optional[int]
|
Truncate strings longer than this length with an ellipsis. |
200
|
stream
|
_Writable
|
Output stream; defaults to sys.stdout. Notes ----- * Colors automatically fall back to plain text if ANSI is not supported. * Errors are logged using 'logging.error(..., exc_info=True)'. |
stdout
|
Source code in src/sciwork/console/printer.py
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
options: members: true show_root_heading: true heading_level: 2
Console¶
Bases: Prompter
High-level console helper that extends :class:Printer with convenience methods
for timing, rules (horizontal lines), and a simple dot-loading animation.
Color Usage¶
The class reuses the :class:Printer palette and will look up optional roles:
-"rule": color for horizontal rules
- "dots": color for the dot animation
If a role is not present in the palette, it falls back to a neutral style.
Source code in src/sciwork/console/prompter.py
40 41 42 43 44 | |
dot_loading_animation(current_count, *, max_dots=5, stream=sys.stdout, color_role='dots', left='', right='')
¶
Print one step of a dot-loading animation and return the updated count. Dots are colorized using a palette role (if color is supported).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_count
|
int
|
Current number of dots already printed in the active cycle. |
required |
max_dots
|
int
|
Maximum dots before resetting. Defaults to 5. |
5
|
stream
|
TextIO
|
Output stream; defaults to |
stdout
|
color_role
|
str
|
Palette role to colorize the dots. Defaults to |
'dots'
|
left
|
str
|
Static text printed to the left of the dots. |
''
|
right
|
str
|
Static text printed to the right of the dots. |
''
|
Returns:
| Type | Description |
|---|---|
int
|
Updated dot counter to be fed back into the next call. |
Source code in src/sciwork/console/console.py
76 77 78 79 80 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 | |
rule(times=1, *, prespace=True, char='-', width=None, stream=sys.stdout, color_role='rule')
¶
Print a colored horizontal rule (optionally multiple times).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times
|
int
|
How many lines to print. Defaults to 1. |
1
|
prespace
|
bool
|
Print a blank line before the rules. Defaults to |
True
|
char
|
str
|
Single character used to build the rule. Defaults to |
'-'
|
width
|
Optional[int]
|
Target width. If omitted, the terminal width is detected (fallback 100). |
None
|
stream
|
TextIO
|
Output stream; defaults to |
stdout
|
color_role
|
str
|
Palette role to colorize the rule. Defaults to |
'rule'
|
Returns:
| Type | Description |
|---|---|
int
|
The width that was used for the rule. |
Source code in src/sciwork/console/console.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
time_count(start_time, end_time, *, ms=False)
staticmethod
¶
Format the elapsed time between two timestamps into a readable string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_time
|
float
|
Start time in seconds (e.g., from |
required |
end_time
|
float
|
End time in seconds. |
required |
ms
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Human-friendly time span, e.g. |
Source code in src/sciwork/console/console.py
27 28 29 30 31 32 33 34 35 36 37 38 | |
options: members: true show_root_heading: true heading_level: 2
Prompter¶
Bases: Printer
Mixin that adds colored prompting utilities to console classes.
This mixin expects the subclass to expose:
self.palette:dict[str, str]with ANSI escapes.self._use_color_flag:booltoggle for color usage.self._supports_color(stream: TextIO, use_color_flag: bool) -> bool
Typically, :class:~sciwork.console.printer.Printer already provides these.
Source code in src/sciwork/console/prompter.py
40 41 42 43 44 | |
confirm(message, *, default=False, stream=sys.stdout, input_func=input, yes_values=('y', 'yes'), no_values=('n', 'no'), transform=lambda s: s.strip().lower())
¶
Ask a yes/no question with a colored prompt and return a boolean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Question to show (e.g., |
required |
default
|
bool
|
Default answer when the user presses Enter. Controls the |
False
|
stream
|
_Stream
|
Output stream (colors are enabled only if TTY / color-capable). |
stdout
|
input_func
|
Callable[[str], str]
|
Input function to call (injectable for test). |
input
|
yes_values
|
Sequence[str]
|
Accepted case-insensitive strings for "yes". |
('y', 'yes')
|
no_values
|
Sequence[str]
|
Accepted case-insensitive strings for "no". |
('n', 'no')
|
transform
|
Callable[[str], str]
|
Normalization function applied to raw input (default: lowercase and strip). |
lambda s: lower()
|
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/sciwork/console/prompter.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | |
print_lines(lines, *, stream=sys.stdout)
¶
Print a block of lines to the console, flushing after each line. Safer on Windows than passing a giant multi-line string into input().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
Iterable of strings to print. |
required |
stream
|
_Writable
|
Output stream; defaults to sys.stdout. |
stdout
|
Source code in src/sciwork/console/prompter.py
56 57 58 59 60 61 62 63 64 65 66 | |
prompt(message, *, default=None, choices=None, validate=None, transform=None, allow_empty=False, retries=3, stream=sys.stdout, input_func=input)
¶
Prompt the user for a line of input with optional validation and coloring.
The prompt can display a default value and a list of choices. It the user
submits an empty line and default is provided, the default is returned.
A validate callback may raise to reject the input; a transform callback
may convert text (e.g. str.strip or str.lower).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Prompt message shown to the user (without trailing colon). |
required |
default
|
Optional[str]
|
Optional default value returned when the user presses Enter on an empty line. |
None
|
choices
|
Optional[Iterable[_T]]
|
Optional finite set of allowed values. If provided, input must be one of these. |
None
|
validate
|
Optional[Callable[[_T], None]]
|
Optional callable |
None
|
transform
|
Optional[Callable[[str], _T]]
|
Optional callable |
None
|
allow_empty
|
bool
|
Allow returning an empty string when no default is set. Defaults to |
False
|
retries
|
int
|
Number of attempts before raising |
3
|
stream
|
_Stream
|
Output stream (colors are enabled only if TTY / color-capable). |
stdout
|
input_func
|
Callable[[str], str]
|
Input function to call (injectable for test). |
input
|
Returns:
| Type | Description |
|---|---|
Union[str, _T]
|
Final (validated and transformed) value. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the user exceeds the allowed number of attempts or input is invalid. |
Source code in src/sciwork/console/prompter.py
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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
options: members: true show_root_heading: true heading_level: 2
Printer¶
Color-aware, nest-friendly pretty printer for Python structures.
Features¶
- Dicts: inline scalars (
key: value), nested values expand with indentation. - Lists/Tuples/Sets: index/marker labels, nested values expand.
- Optional ANSI color (auto disabled when the stream is not a TTY).
- Optional type hints (
(str),(int), ...). - String truncation for long values.
Notes¶
The color palette is loaded from ansi_colors.json which is ensured on first
use via :func:sciwork.console.create_ansi_colors_config. The default location is
<cwd>/sciwork/configs/ansi_colors.json; switch to the user location by
calling :class:Printer with prefer='user'.
Source code in src/sciwork/console/printer.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
__enter__()
¶
Enter context.
Saves actual "user-adjustable" states so that they are renewed by exit. Attributes are changeable within the block: with printer as p: p._use_color_flag = False p.printer(obj)
Source code in src/sciwork/console/printer.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
__exit__(exc_type, exc_val, exc_tb)
¶
Exit context: renews the state before entering the block.
Returns:
| Type | Description |
|---|---|
bool
|
False. |
Source code in src/sciwork/console/printer.py
84 85 86 87 88 89 90 91 92 93 94 95 96 | |
__repr__()
¶
Unambiguous representation of printer.
Source code in src/sciwork/console/printer.py
57 58 59 60 61 | |
__str__()
¶
Concise representation of printer.
Source code in src/sciwork/console/printer.py
63 64 65 66 | |
printer(obj, indent=0, sort_keys=True, show_types=False, max_str=200, stream=sys.stdout)
¶
Pretty-prints nested Python structures (dict, list, tuple, set, etc.) with inline keys/indices on the same line. Supports optional color, type hints, sorting of dict keys, and string truncation for readability.
Behavior¶
- Dicts: 'key: value' on a single line when value is scalar; nested values expand with indentation.
- Lists: '[idx]: value' on a single line when scalar; nested values expand.
- Tuples: '(idx): value' labels.
- Sets: '{•}: value' labels (order not guaranteed; sorted when possible).
- Scalars: printed directly; long strings are truncated to 'max_str' characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Object to be printed. |
required |
indent
|
int
|
Current indentation level (internal for recursion). |
0
|
sort_keys
|
bool
|
Sort dictionary keys alphabetically (safe if keys are comparable). |
True
|
show_types
|
bool
|
Append the value's type in a dim style, e.g., '(str)'. |
False
|
max_str
|
Optional[int]
|
Truncate strings longer than this length with an ellipsis. |
200
|
stream
|
_Writable
|
Output stream; defaults to sys.stdout. Notes ----- * Colors automatically fall back to plain text if ANSI is not supported. * Errors are logged using 'logging.error(..., exc_info=True)'. |
stdout
|
Source code in src/sciwork/console/printer.py
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
options: members: true show_root_heading: true heading_level: 2
Base helpers¶
format_interval(start_time, end_time, *, ms=False)
¶
Format the elapsed time between two timestamps into a readable string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_time
|
float
|
Start time in seconds (e.g., from |
required |
end_time
|
float
|
End time in seconds. |
required |
ms
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Human-friendly time span, e.g. |
Source code in src/sciwork/console/base.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
next_dots(current_count, *, max_dots=5, stream=sys.stdout, prefix='', suffix='')
¶
Print a simple dot-loading animation step and return the updated count.
The function prints one dot each call until max_dots is reached, then
clears the line segment and starts over.
prefix and suffix are optional strings that are printed before and after
and are visually static.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_count
|
int
|
Current number of dots already printed in the active cycle. |
required |
max_dots
|
int
|
Maximum dots before resetting. Defaults to 5. |
5
|
stream
|
_Stream
|
Destination stream; defaults to |
stdout
|
prefix
|
str
|
Optional text/ANSI printed before the dots. |
''
|
suffix
|
str
|
Optional text/ANSI printed after the dots. |
''
|
Returns:
| Type | Description |
|---|---|
int
|
Updated dot counter to be fed back into the next call. |
Source code in src/sciwork/console/base.py
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 | |
print_rule(times=1, *, prespace=True, char='-', width=None, stream=sys.stdout, prefix='', suffix='')
¶
Print a horizontal rule (optionally multiple times).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times
|
int
|
How many lines to print. Defaults to 1. |
1
|
prespace
|
bool
|
Print a blank line before the rules. Defaults to |
True
|
char
|
str
|
Single character used to build the rule. Defaults to |
'-'
|
width
|
Optional[int]
|
Target width. If omitted, the terminal width is detected (fallback 100). |
None
|
stream
|
_Stream
|
Destination stream; defaults to |
stdout
|
prefix
|
str
|
Optional string printed before the rule (e.g., ANSI color). |
''
|
suffix
|
str
|
Optional string printed after the rule (e.g., reset color). |
''
|
Returns:
| Type | Description |
|---|---|
int
|
The width that was used for the rule. |
Source code in src/sciwork/console/base.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | |
options: members: true show_root_heading: true heading_level: 2
Bootstrap¶
ensure_ansi_colors(*, prefer='project', overwrite=False)
¶
Ensure an ansi_colors.json exists and return its absolute path.
The file is created using a minimal default palette unless it already exists
(unless overwrite=True). By default, it is placed under
<cwd>/sciwork/configs/ansi_colors.json; pass prefer='user' to use a
per-user config location (~/.config/sciwork/ or %APPDATA%\sciwork\ on Windows).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefer
|
Literal['project', 'user']
|
Where to create/read the file ( |
'project'
|
overwrite
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
Path
|
Absolute path to the JSON file. |
Raises:
| Type | Description |
|---|---|
OSError
|
On filesystem errors when creating directories or writing the file. |
Source code in src/sciwork/console/bootstrap.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
options: members: true show_root_heading: true heading_level: 2