Skip to content

Instantly share code, notes, and snippets.

@sebastiancarlos
Created January 19, 2024 15:30
Show Gist options
  • Save sebastiancarlos/ac634f6f705b73f5e5fbb819986f2b6e to your computer and use it in GitHub Desktop.
Save sebastiancarlos/ac634f6f705b73f5e5fbb819986f2b6e to your computer and use it in GitHub Desktop.
Pretty printer with color, label and value (value defaults to evaluation of label)
# explicitly define the interface
__all__ = ["pretty_print"]
def is_package_available(package_name):
import importlib.util
package_spec = importlib.util.find_spec(package_name)
return package_spec is not None
def pretty_print(label: str, value: any = "") -> None:
""" Prints "label". Followed by pretty printed "value".
If "value" is not passed, evaluates "label" in the calling stack and prints
that instead.
Example:
>>> pretty_print("dir()") # with color output!
dir():
['__annotations__',
'__builtins__',
...
"""
from inspect import currentframe
# If available, use rich to format value. Otherwise, use pprint.
if is_package_available("rich"):
from rich.console import Console
def pformat(value):
console = Console()
with console.capture() as capture:
console.print(value)
output = capture.get()
# for some reason this output has a trailing newline, remove it
return output[:-1]
else:
from pprint import pformat
# If value is not passed, evaluate label (in the caller's namespace)
if value == "":
frame = currentframe().f_back
value = eval(label, frame.f_globals, frame.f_locals)
del frame
value_output = pformat(value)
# If value is multiline, value comes after newline.
# Otherwise, value comes after space.
separator = "\n" if "\n" in value_output else " "
green="\033[0;32m"
bold="\033[1m"
reset="\033[0m"
print(f"{green}{bold}{label}:{reset}{separator}{value_output}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment