Is there any way of changing the way a int
-type object is converted to string when calling repr
or pprint.pformat
, such that
repr(dict(a=5, b=100))
will give "{a: 0x5, b: 0x64}"
instead of "{a: 5, b: 100}"
?
I suppose subclassing the int
type would be an option:
class IntThatPrintsAsHex(int):
def __repr__(self):
return hex(self)
def preprocess_for_repr(obj):
if isinstance(obj, dict):
return {preprocess_for_repr(k): preprocess_for_repr(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [preprocess_for_repr(e) for e in obj]
elif isinstance(obj, tuple):
return tuple(preprocess_for_repr(e) for e in obj)
elif isinstance(obj, int) and not isinstance(obj, bool):
return IntThatPrintsAsHex(obj)
elif isinstance(obj, set):
return {preprocess_for_repr(e) for e in obj}
elif isinstance(obj, frozenset):
return frozenset(preprocess_for_repr(e) for e in obj)
else: # I hope I didn't forget any.
return obj
print(repr(preprocess_for_repr(dict(a=5, b=100))))
But as you can see, the preprocess_for_repr
function is rather unpleasant to keep "as-complete-as-needed" and to work with. Also, the obvious performance implications.