Skip to content Skip to sidebar Skip to footer

Override __repr__ Or Pprint For Int

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}' i

Solution 1:

int is a builtin type and you can't set attributes of built-in/extension types (you can not override nor add new methods to these types). You could however subclass int and override the __repr__ method like this:

classInteger(int):
     def__repr__(self):
         returnhex(self)

 x = Integer(3)
 y = Integer(100)

 # prints "[0x3, 0x64]"print [x,y]

Integer will behave exactly like an int, except for the __repr__ method. You can use it index lists, do math and so on. However unless you override them, math operations will return regular int results:

>>> print [x,y,x+1,y-2, x*y]
[0x3, 0x64, 4, 98, 300]

Solution 2:

You should be able to monkey patch the pprint module to have integers print the way you want, but this isn't really a good approach.

If you're just looking for a better representation of integers for debugging, IPython has its own pretty printer that is easily customizable through its pretty module:

In [1]: from IPython.lib import pretty

In [2]: pretty.for_type(int, lambda n, p, cycle: p.text(hex(n)))
Out[2]: <function IPython.lib.pretty._repr_pprint>In [3]: 123Out[3]: 0x7bIn [4]: x = [12]

In [5]: x
Out[5]: [0xc]

In [6]: pretty.pretty(x)
Out[6]: '[0xc]'

You can read more about the three parameters in the linked documentation.

Post a Comment for "Override __repr__ Or Pprint For Int"