stouputils.print.colorizer module#
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. .. rubric:: Examples
>>> 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]#
“.
- Type:
Matches a token holding a quoted string, ex
- Type:
“‘some name’
- NUMBER_PATTERN: ClassVar[Pattern[str]] = re.compile('(\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)')[source]#
the two numbers of “scale=(0.5,”.
- Type:
Matches a number anywhere inside a token, ex
- 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
Examples
>>> 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
Examples
>>> 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
Examples
>>> 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