Skip to content

Instantly share code, notes, and snippets.

@EdwardBetts
Last active January 21, 2026 17:25
Show Gist options
  • Select an option

  • Save EdwardBetts/0814484fdf7bbf808f6f to your computer and use it in GitHub Desktop.

Select an option

Save EdwardBetts/0814484fdf7bbf808f6f to your computer and use it in GitHub Desktop.
Python pprint with color syntax highlighting for the console
from pprint import pformat
from typing import Any
from pygments import highlight
from pygments.formatters import Terminal256Formatter
from pygments.lexers import PythonLexer
def pprint_color(obj: Any) -> None:
"""Pretty-print in color."""
print(highlight(pformat(obj), PythonLexer(), Terminal256Formatter()), end="")
@panzi
Copy link

panzi commented Jan 21, 2026

Thank you! I've added some more options and made color mode automatic per default:

import sys

from pprint import pformat, pprint
from typing import Literal, IO, Any

from pygments import highlight
from pygments.formatter import Formatter
from pygments.formatters import get_formatter_by_name
from pygments.lexers import PythonLexer

__all__ = (
    'xpprint',
    'xpp',
)

def xpprint(
    obj: Any,
    stream: IO[str]|None = None,
    indent: int = 1,
    width: int = 80,
    depth: int|None = None,
    *,
    compact: bool = False,
    sort_dicts: bool = True,
    underscore_numbers: bool = False,
    color: Literal['auto', 'always', 'never'] = 'auto',
    formatter: str|Formatter = 'console',
) -> None:
    if color == 'always' or (color == 'auto' and (stream or sys.stdout).isatty()):
        fmt = get_formatter_by_name(formatter) if isinstance(formatter, str) else formatter

        print(highlight(
            pformat(
                obj,
                indent=indent,
                width=width,
                depth=depth,
                compact=compact,
                sort_dicts=sort_dicts,
                underscore_numbers=underscore_numbers,
            ),
            PythonLexer(),
            fmt
        ), end="", file=stream)
    else:
        pprint(
            obj,
            stream=stream,
            indent=indent,
            width=width,
            depth=depth,
            compact=compact,
            sort_dicts=sort_dicts,
            underscore_numbers=underscore_numbers,
        )

xpp = xpprint

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment