Skip to content

Python pretty print in hex

I recently needed to pretty print something from Python, but I needed the integers printed in hex rather than decimal. I overloaded the PrettyPrinter class to do it. Here’s how:


#!/usr/bin/env python3
from pprint import PrettyPrinter

class HexPrettyPrinter(PrettyPrinter):
def format(self, object, context, maxlevels, level):
repr, readable, recursive = PrettyPrinter.format(self, object, context, maxlevels, level)
if isinstance(object, int):
return “{0:x}”.format(object), readable, recursive
else:
return repr, readable, recursive

You’d do something like this (untested):

from hex_pprint import HexPrettyPrinter
hpp = HexPrettyPrinter()
hpp.pprint([1, 2, 3, 4, dict(a=1,b=2)])

Be the first to like.

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*