Skip to content

Instantly share code, notes, and snippets.

@sapslaj
Last active May 18, 2024 00:47
Show Gist options
  • Save sapslaj/c189662fb81b73fba17cdc81b697f3a9 to your computer and use it in GitHub Desktop.
Save sapslaj/c189662fb81b73fba17cdc81b697f3a9 to your computer and use it in GitHub Desktop.
Pretty print Python object with Black
import black
import black.mode
def pprint(o):
mode = black.mode.Mode(target_versions={black.mode.TargetVersion.PY311})
print(black.format_str(repr(o), mode=mode))
# Configuration file for ipython.
# $ ipython profile create
# $ vim ~/.ipython/profile_default/ipython_config.py
try:
import black
import black.mode
import IPython.lib.pretty
import pygments
from pygments.lexers import PythonLexer
from pygments.formatters import TerminalFormatter
import textwrap
class BlackRepresentationPrinter:
def __init__(self, stream, *args, **kwargs):
self.stream = stream
self.mode = black.mode.Mode(target_versions={black.mode.TargetVersion.PY311})
self.lexer = PythonLexer()
self.formatter = TerminalFormatter() # replace with Terminal256Formatter or TerminalTrueColorFormatter if you prefer
def __black_format(self, obj, level=0):
indent = " " * level
result = repr(obj)
try:
result = black.format_str(result, mode=self.mode)
except Exception:
if isinstance(obj, dict):
result = "{\n"
for key, value in obj.items():
result += self.__black_format(key, level=1).rstrip()
result += ": "
result += self.__black_format(value, level=1).strip()
result += ",\n"
result += "}\n"
elif isinstance(obj, list):
result = "[\n"
for value in obj:
result += self.__black_format(value, level=1)
result += ",\n"
result += "]\n"
elif isinstance(obj, set):
result = "{\n"
for value in obj:
result += self.__black_format(value, level=1)
result += ",\n"
result += "}\n"
elif isinstance(obj, tuple):
result = "(\n"
for value in obj:
result += self.__black_format(value, level=1)
result += ",\n"
result += ")\n"
return textwrap.indent(result, indent)
def __pygments_highlight(self, result):
try:
result = pygments.highlight(result, lexer=self.lexer, formatter=self.formatter) # optional, if you want syntax highlighting too
except Exception:
pass
return result
def pretty(self, obj):
prettied = self.__black_format(obj)
prettied = self.__pygments_highlight(prettied)
self.stream.write(prettied.rstrip())
def flush(self):
pass
IPython.lib.pretty.RepresentationPrinter = BlackRepresentationPrinter
except ImportError:
pass
c = get_config() #noqa
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment