Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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="")
@RyanFleck
Copy link

RyanFleck commented Oct 3, 2018

Thanks a bunch! Works well in Jupyter notebooks. (Extra parentheses needed for Python 3.)

@idobarnoam
Copy link

idobarnoam commented Apr 15, 2019

Thanks for this!

@laike9m
Copy link

laike9m commented Apr 11, 2020

Thanks!

@laknath
Copy link

laknath commented Jun 14, 2020

Thanks!

@Rainymood
Copy link

Rainymood commented May 17, 2022

Doesn't work for me in python 3.8 in a jupyter notebook

@jasonk
Copy link

jasonk commented Aug 21, 2022

It doesn't work in newer versions because python no longer allows you to call print without parentheses. Just add parentheses to the last line and it will work:

    print( highlight(pformat(obj), PythonLexer(), Terminal256Formatter()) )

@EdwardBetts
Copy link
Author

EdwardBetts commented Aug 22, 2022

I've updated the gist for Python 3 and added type hints.

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