🖨️ print#
This module provides utility functions for printing messages with different levels of importance.
If a message is printed multiple times, it will be displayed as “(xN) message” where N is the number of times the message has been printed.
The module also includes a colored() function, which colors text in the Python 3.14 style:
file paths, line numbers and function names in magenta, and exception names in bold magenta.
All functions have their colored counterparts with a ‘c’ suffix (e.g., infoc(), debugc(), etc.)
import stouputils as stp
# The same message several times in a row shows once, with (x3)
for _ in range(3):
stp.info("Downloading", "dataset.zip")
# One function per level, each with its own color
stp.debug("Cache hit for", "model.pt")
stp.suggestion("Pass num_workers=8 to load faster")
stp.progress("Epoch 3/10 done")
stp.warning("Learning rate looks high")
stp.error("Checkpoint not found", exit=False) # exit=True would also stop the program
# Describe any value: its type, its size and its content
stp.whatisit({"lr": 0.1, "epochs": 10})
# The "c" versions highlight exception names, line numbers and file paths
stp.infoc("ValueError raised in load_data() at line 42 of ./train.py")
color_formatting#
- format_colored(
- *values: Any,
- color: str = '\x1b[95m',
Format text with Python 3.14 style colored formatting.
Dynamically colors text by analyzing each word: - File paths in the specified color - Numbers in the specified color - Function names (built-in and callable objects) in the specified color - Exception names in bold with the specified color
- Parameters:
values – Values to format (like the print function)
color – ANSI color code to use for coloring (default: Cfg.MAGENTA)
- Returns:
The formatted text with ANSI color codes
>>> # Test function names with parentheses >>> result = format_colored("Call print() with 42 items") >>> m, r, b = Cfg.MAGENTA, Cfg.RESET, Cfg.BOLD >>> result == f"Call {m}print{r}() with {m}42{r} items" True
>>> # Test function names without parentheses >>> result = format_colored("Use len and sum functions") >>> result == f"Use {m}len{r} and {m}sum{r} functions" True
>>> # Test exceptions (bold magenta) >>> result = format_colored("Got ValueError when parsing") >>> result == f"Got {b}{m}ValueError{r} when parsing" True
>>> # Test file paths >>> result = format_colored("Processing ./data.csv file") >>> result == f"Processing {m}./data.csv{r} file" True >>> result = format_colored("Processing ./data/some/sub/directory") >>> result == f"Processing {m}./data/some/sub/directory{r}" True >>> result = format_colored("This is not a path: batches/images") >>> result == "This is not a path: batches/images" True
>>> # Test file paths with quotes >>> result = format_colored('File "/path/to/script.py" line 42') >>> result == f'File {m}"/path/to/script.py"{r} line {m}42{r}' True
>>> # Test numbers >>> result = format_colored("Found 100 items and 3.14 value, 3.0e+10 is big") >>> result == f"Found {m}100{r} items and {m}3.14{r} value, {m}3.0e+10{r} is big" True
>>> # Test numbers embedded in non-numeric tokens (both must be colored the same) >>> result = format_colored("scale=(0.5, 0.5), overlap=(0.0, 0.0)") >>> result == f"scale=({m}0.5{r}, {m}0.5{r}), overlap=({m}0.0{r}, {m}0.0{r})" True >>> result = format_colored("took: 2.885ms") >>> result == f"took: {m}2.885{r}ms" True
>>> # Test mixed content >>> result = format_colored("Call sum() got IndexError at line 256 in utils.py") >>> result == f"Call {m}sum{r}() got {b}{m}IndexError{r} at line {m}256{r} in utils.py" True
>>> # Test keywords always colored >>> result = format_colored("Check class dtype type") >>> result == f"Check {m}class{r} {m}dtype{r} {m}type{r}" True
>>> # Test plain text (no coloring) >>> result = format_colored("This is plain text") >>> result == "This is plain text" True
>>> # Affix punctuation should not be colored (assert exact coloring, punctuation uncolored) >>> result = format_colored("<class") >>> result == f"<{m}class{r}" True >>> result = format_colored("(dtype:") >>> result == f"({m}dtype{r}:" True >>> result = format_colored("[1.") >>> result == f"[{m}1{r}." True
>>> # Test complex >>> text = "<class 'numpy.ndarray'>, <id 14036>: (dtype: float32, shape: (6,), min: 0.0, max: 1.0) [1. 0. 0. 0. 1. 0.]" >>> result = format_colored(text) >>> result == f"<{m}class{r} {m}'numpy.ndarray'{r}>, <{m}id{r} {m}14036{r}>: ({m}dtype{r}: float{m}32{r}, shape: ({m}6{r},), {m}min{r}: {m}0.0{r}, {m}max{r}: {m}1.0{r}) [{m}1{r}. {m}0{r}. {m}0{r}. {m}0{r}. {m}1{r}. {m}0{r}.]" True >>> result = format_colored("Specimen: 'C-B250021834A02HES002-NH4': 24.29029s") >>> result == f"Specimen: {m}'C-B250021834A02HES002-NH4'{r}: {m}24.29029{r}s" True
- colored(
- *values: Any,
- file: TextIO | None = None,
- **print_kwargs: Any,
Print with Python 3.14 style colored formatting.
Dynamically colors text by analyzing each word: - File paths in magenta - Numbers in magenta - Function names (built-in and callable objects) in magenta - Exception names in bold magenta
- Parameters:
values – Values to print (like the print function)
file – File to write the message to (default: sys.stdout)
print_kwargs – Keyword arguments to pass to the print function
import stouputils as stp # Exception names, numbers, file paths and known functions get highlighted stp.colored("Traceback: ValueError raised at line 42 of ./data/train.py") stp.colored("Call len() on the list before passing it to sorted()") stp.colored("KeyboardInterrupt after 3.5 seconds, 120 of 500 files processed")
colorizer#
Word by word coloring used by the print helpers.
Every predicate here works on a single whitespace separated token, so the caller only has to split the text once and join the results back.
- class WordColorizer(color: str = '\x1b[95m')[source]#
Bases:
objectColors the tokens of a text, one word at a time.
>>> WordColorizer().colorize_text("Found 42 items") == f"Found {Cfg.MAGENTA}42{Cfg.RESET} items" True
- EXCEPTION_NAMES: ClassVar[frozenset[str]] = frozenset({'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'NotADirectoryError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError'})[source]#
Every built-in exception name, colored in bold.
- BUILTIN_FUNCTIONS: ClassVar[frozenset[str]] = frozenset({'__build_class__', '__import__', '__loader__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'})[source]#
Every built-in callable that is not an exception.
- KEYWORDS: ClassVar[frozenset[str]] = frozenset({'class', 'dtype', 'type'})[source]#
Words always colored, whatever they look like.
- AFFIX_PATTERN: ClassVar[Pattern[str]] = re.compile('^(\\W*)(.*?)(\\W*)$', re.ASCII)[source]#
Splits a token into leading punctuation, core text and trailing punctuation.
- QUOTED_PATTERN: ClassVar[Pattern[str]] = re.compile('^(\\W*?)(\'[^\']*\'|\\"[^\\"]*\\")(\\W*)$')[source]#
Matches a token holding a quoted string, ex: “‘some name’:”.
- NUMBER_PATTERN: ClassVar[Pattern[str]] = re.compile('(\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)')[source]#
Matches a number anywhere inside a token, ex: the two numbers of “scale=(0.5,”.
- WORD_SPLIT_PATTERN: ClassVar[Pattern[str]] = re.compile('(\\s+)')[source]#
Splits a text into tokens, keeping the whitespace as tokens of its own.
- wrap(text: str, bold: bool = False) str[source]#
Surround a text with the color code and the reset code.
- Parameters:
text – Text to color
bold – Whether the text is also written in bold
- Returns:
Colored text
- static is_filepath(word: str) bool[source]#
Check if a word looks like a file path.
- Parameters:
word – Token to check, quotes included
- Returns:
Whether the token looks like a path
>>> WordColorizer.is_filepath("./data.csv"), WordColorizer.is_filepath("batches/images") (True, False)
- static is_number(word: str) bool[source]#
Check if a word is a number.
- Parameters:
word – Token to check
- Returns:
Whether the token parses as a float
>>> WordColorizer.is_number("3.0e+10"), WordColorizer.is_number("42ms") (True, False)
- static alphanumeric_of(word: str) str[source]#
Keep only the alphanumeric characters of a word, ex: “(ValueError:” gives “ValueError”.
- static function_name_of(word: str) str[source]#
Function name held by a word, empty when there is none.
- Parameters:
word – Token to check
- Returns:
“print” for “print()”
- Return type:
Name of the called function, ex
>>> WordColorizer.function_name_of("print()"), WordColorizer.function_name_of("nothing") ('print()', '')
- colorize_function(core: str) str[source]#
Color the function name held by a token, leaving the rest of the token untouched.
- Parameters:
core – Token without its leading and trailing punctuation
- Returns:
Token with its function name colored
- colorize_core(core: str) str | None[source]#
Color a token stripped from its punctuation, or return None when nothing matches.
- Parameters:
core – Token without its leading and trailing punctuation
- Returns:
Colored token, or None when the token deserves no color
common#
- class PrintMemory[source]#
Bases:
objectClass to store shared variables for print functions.
- previous_args_kwards: tuple[Any, Any] = (("Sorted minor versions: ['26.12', '26.11', '26.10', '26.9', '26.8', '26.7', '26.6', '26.5', '26.4', '26.3', '26.2', '26.1', '26.0', '1.31', '1.30', '1.29', '1.28', '1.27', '1.26', '1.25', '1.24', '1.23', '1.22', '1.21', '1.20', '1.19', '1.18', '1.17', '1.16', '1.15', '1.14']",), {'color': '\x1b[92m', 'prefix': '', 'text': 'INFO '})[source]#
Store the previous print call’s args and kwargs for comparison in is_same_print()
debugging#
- whatisit(*values: ~typing.Any, print_function: ~collections.abc.Callable[[...], None] = <function debug>, flush: bool = True, max_length: int = 250, color: str = '\x1b[96m', text: str = 'What is it?', **print_kwargs: ~typing.Any) None[source]#
Print the type of each value and the value itself, with its id and length/shape.
The output format is: “type, <id id_number>: (length/shape) value”
- Parameters:
values – Values to print
print_function – Function to use to print the values (default: debug())
max_length – Maximum length of the value string to print (default: 250)
color – Color of the message (default: CYAN)
text – Text in the message (replaces “DEBUG”)
print_kwargs – Keyword arguments to pass to the print function
- describe_value(
- value: Any,
- max_length: int = 250,
The line
whatisit()prints for one value:type, <id id_number>: (metadata) value.- Parameters:
max_length – Characters of the value’s string kept, the rest being replaced by
....
- value_metadata(value: Any) list[str][source]#
What a value exposes among dtype, size in bytes, device, shape or length, and its min and max, as
"name: value".A CPU device is left out, and min and max only appear when they differ.
>>> value_metadata([1, 5, 3]) ['length: 3', 'min: 1', 'max: 5'] >>> value_metadata("abc") ['length: 3']
- first_attribute_entry(
- value: Any,
- names: tuple[str, ...],
"name: value"for the first of these attributes the value holds, None when it holds none or its device is the CPU.
- breakpoint(*values: ~typing.Any, print_function: ~collections.abc.Callable[[...], None] = <function warning>, flush: bool = True, max_length: int = 1000, color: str = '\x1b[96m', text: str = 'BREAKPOINT (press Enter)', **print_kwargs: ~typing.Any) None[source]#
Breakpoint function, pause the program and print the values.
- Parameters:
values – Values to print
print_function – Function to use to print the values (default: warning())
max_length – Maximum length of the value string to print (default: 1000)
color – Color of the message (default: CYAN)
text – Text in the message (replaces “WARNING”)
print_kwargs – Keyword arguments to pass to the print function
message#
- info(
- *values: Any,
- color: str = '\x1b[92m',
- text: str = 'INFO ',
- prefix: str = '',
- file: TextIO | list[TextIO] | None = None,
- use_colored: bool = False,
- **print_kwargs: Any,
Print an information message looking like “[INFO HH:MM:SS] message” in green by default.
- Parameters:
values – Values to print (like the print function)
color – Color of the message (default: GREEN)
text – Text of the message (default: “INFO “)
prefix – Prefix to add to the values
file – File(s) to write the message to (default: sys.stdout)
use_colored – Whether to use the
colored()function to format the messageprint_kwargs – Keyword arguments to pass to the print function
- debug(
- *values: Any,
- flush: bool = True,
- color: str = '\x1b[96m',
- text: str = 'DEBUG',
- **print_kwargs: Any,
Print a debug message looking like “[DEBUG HH:MM:SS] message” in cyan by default.
- alt_debug(
- *values: Any,
- flush: bool = True,
- color: str = '\x1b[94m',
- text: str = 'DEBUG',
- **print_kwargs: Any,
Print a debug message looking like “[DEBUG HH:MM:SS] message” in blue by default.
- suggestion(
- *values: Any,
- flush: bool = True,
- color: str = '\x1b[96m',
- text: str = 'SUGGESTION',
- **print_kwargs: Any,
Print a suggestion message looking like “[SUGGESTION HH:MM:SS] message” in cyan by default.
- progress(
- *values: Any,
- flush: bool = True,
- color: str = '\x1b[95m',
- text: str = 'PROGRESS',
- **print_kwargs: Any,
Print a progress message looking like “[PROGRESS HH:MM:SS] message” in magenta by default.
- warning(
- *values: Any,
- flush: bool = True,
- color: str = '\x1b[93m',
- text: str = 'WARNING',
- **print_kwargs: Any,
Print a warning message looking like “[WARNING HH:MM:SS] message” in yellow by default and in sys.stderr.
- error(
- *values: Any,
- exit: bool = False,
- flush: bool = True,
- color: str = '\x1b[91m',
- text: str = 'ERROR',
- **print_kwargs: Any,
Print an error message (in sys.stderr and in red by default) and optionally ask the user to continue or stop the program.
- Parameters:
values – Values to print (like the print function)
exit – Whether to ask the user to continue or stop the program, false to ignore the error automatically and continue
flush – Whether to flush the output
color – Color of the message (default: RED)
text – Text in the message (replaces “ERROR “)
print_kwargs – Keyword arguments to pass to the print function
output_stream#
- LINE_TOKENS_RE: Pattern[str] = re.compile('(\\n|\\r|\\x1b\\[\\d*[AB])')[source]#
Splits a text around what moves a terminal cursor: newlines, carriage returns and line moves.
- REDRAW_CHECKPOINT_SECONDS: float = 60.0[source]#
Interval at which a file receives the current state of a line still being redrawn, such as a long progress bar.
- class LineState(
- checkpoint_seconds: float = 60.0,
- mode: Literal['start', 'text', 'redraw', 'repeat'] = 'start',
- buffer: str = '',
- shown: bool = False,
- carriage: bool = False,
- held_repeat: str = '',
- since: float = 0.0,
Bases:
objectWhere a non-terminal output stands in the line one thread is writing, so it receives what a terminal ends up showing.
Text is held until its line ends or the stream is flushed, like a terminal’s line-buffered stdout. Lines from several threads therefore never cut into each other. A line drawn again after a carriage return, such as a progress bar, is written once in its final state, plus every
checkpoint_secondswhile it lasts. A line starting with a cursor move rewrites the previous one, as stouputils does for a repeated message, and the last of such a series is written when the series ends.>>> state = LineState() >>> state.feed("\r 10%") + state.feed("\r100%\n") + state.feed("done\n") '100%\ndone\n' >>> state.feed("same\n") + state.feed("\x1b[1Asame (x2)\n") + state.feed("\x1b[1Asame (x3)\n") + state.feed("other\n") 'same\nsame (x3)\nother\n' >>> state.feed("Processing..."), state.flush(), state.feed(" done\n") ('', 'Processing...', ' done\n')
- mode: Literal['start', 'text', 'redraw', 'repeat'] = 'start'[source]#
What the current line is: not started, plain text, drawn again after a carriage return, or rewriting the previous line.
- buffer: str = ''[source]#
Text of the current line not written yet, its last drawing for a redrawn line.
- carriage: bool = False[source]#
Whether a carriage return came since the last text, so the next text draws the line again.
- take(token: str) str[source]#
What the output receives of one token: a newline, a carriage return, a line move or plain text.
- draw(token: str) str[source]#
Add text to the current line, a carriage return before it starting the drawing over.
- flush() str[source]#
The unwritten text of a plain line, which a terminal shows on flush, so a step announced without newline shows.
- class TeeTarget(file: ~typing.IO[~typing.Any], thread: int | None = None, strip_colors: bool = True, ascii_only: bool = True, ignore_lineup: bool = True, lines: dict[int, ~stouputils.print.output_stream.LineState] = <factory>, lock: ~_thread.allocate_lock = <factory>)[source]#
Bases:
objectOne output of a
TeeMultiOutput, with how it is written to and which thread it listens to.- ascii_only: bool = True[source]#
Whether non-ASCII characters are replaced, when the output is not a terminal.
- ignore_lineup: bool = True[source]#
Whether the output receives what a terminal ends up showing, when it is not a terminal itself.
- terminal: bool[source]#
Whether the output is a terminal, read once since asking costs a system call.
- write(obj: str) int | None[source]#
Write the text as this output receives it.
- Returns:
Characters written, or None when the output is closed and has to be dropped.
- finish() None[source]#
Write what every thread’s current line still holds back, as when the stream ends.
- class TeeMultiOutput(
- *files: IO[Any],
- strip_colors: bool = True,
- ascii_only: bool = True,
- ignore_lineup: bool = True,
Bases:
objectFile-like object that duplicates output to multiple file-like objects.
Outputs can be added and removed while it is in place, each one listening to every thread or to a single one.
- Parameters:
*files – One or more file-like objects that have write and flush methods
strip_colors – Strip ANSI color codes from output sent to these files
ascii_only – Replace non-ASCII characters with their ASCII equivalents for non-stdout/stderr files
ignore_lineup – Write to non-terminal outputs what a terminal ends up showing, see
LineState
>>> import sys >>> f = open("logfile.txt", "w") >>> sys.stdout = TeeMultiOutput(sys.stdout, f) >>> print("Hello World") # Output goes to both console and file Hello World >>> f.close() # TeeMultiOutput will handle any future writes to closed files gracefully
- targets: tuple[TeeTarget, ...][source]#
Outputs written to, the first one standing for the stream this object replaces
- removable: bool[source]#
Whether
LogToFileput it in place, and takes it away with the last file it holds
- property encoding: str[source]#
Get the encoding of the first file, or “utf-8” as fallback. :returns: “utf-8”, “ascii”, “latin1”, etc. :rtype: The encoding, ex
- write(obj: str) int[source]#
Write the object to every output listening to the current thread.
- Parameters:
obj – String to write
- Returns:
Number of characters written to the first file
- add_file(
- file: IO[Any],
- thread: int | None = None,
- strip_colors: bool = True,
- ascii_only: bool = True,
- ignore_lineup: bool = True,
Start writing to one more output.
- Parameters:
thread – Thread identifier whose writes alone it receives, None for every thread.
progress_tqdm#
- progress_bar(
- iterable: Iterable,
- desc: str = 'Processing',
- color: str = '\x1b[95m',
- bar_format: str = '{l_bar}{bar}\x1b[95m| {n_fmt}/{total_fmt} [{rate_fmt}{postfix}, {elapsed}<{remaining}]\x1b[0m',
- ascii: bool = False,
- smooth_tqdm: bool = True,
- **kwargs: Any,
Function to iterate over a list with a colored TQDM progress bar like the other functions in this module.
- Parameters:
iterable – List to iterate over
desc – Description of the function execution displayed in the progress bar
color – Color of the progress bar (Defaults to ::attr::MAGENTA)
bar_format – Format of the progress bar (Defaults to ::attr::BAR_FORMAT)
ascii – Whether to use ASCII or Unicode characters for the progress bar (Defaults to False)
smooth_tqdm – Whether to enable smooth progress bar updates by setting miniters=1 and mininterval=0.0 (Defaults to True)
**kwargs – Additional arguments to pass to the TQDM progress bar
- Yields:
Each item of the iterable
>>> import time >>> for i in progress_bar(range(10), desc="Time sleeping loop"): ... time.sleep(0.01) >>> # Time sleeping loop: 100%|██████████████████| 10/10 [ 95.72it/s, 00:00<00:00]
utils#
- remove_colors(text: str) str[source]#
Remove the colors from a text. See
remove_ansi()to remove all ANSI escape sequences>>> remove_colors("\x1b[91mHello\x1b[0m") 'Hello' >>> remove_colors("\x1b[1m\x1b[95mBold Magenta Text\x1b[0m") 'Bold Magenta Text' >>> remove_colors("No colors here") 'No colors here' >>> remove_colors("\x1b[91mRed\x1b[0m and \x1b[92mGreen\x1b[0m") 'Red and Green'
Other ANSI escape codes (e.g., cursor movement) are not removed since they are not colors:
>>> remove_colors("Line 1\x1b[1ALine 2 \x1b[31mRed Text\x1b[0m") 'Line 1\x1b[1ALine 2 Red Text'
- remove_ansi(
- text: str,
- pattern: str = '\\x1b\\[[0-?]*[ -/]*[@-~]',
Remove all ANSI escape sequences from a text. See
remove_colors()to remove only color codes.>>> remove_ansi("\x1b[91mHello\x1b[0m") 'Hello' >>> remove_ansi("\x1b[1m\x1b[95mBold Magenta Text\x1b[0m") 'Bold Magenta Text' >>> remove_ansi("No ANSI here") 'No ANSI here' >>> remove_ansi("\x1b[91mRed\x1b[0m and \x1b[92mGreen\x1b[0m") 'Red and Green' >>> remove_ansi("Line 1\x1b[1ALine 2") 'Line 1Line 2' >>> remove_ansi("Hello\x1b[2JWorld") 'HelloWorld'