Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python console default hex display

I'm doing a bunch of work in the Python console, and most of it is referring to addresses, which I'd prefer to see in hex.

So if a = 0xBADF00D, when I simply enter Python> a into the console to view its value, I'd prefer python to reply with 0xBADF00D instead of 195948557.

I know I can enter '0x%X' % a to see it in hex, but I'm looking for some sort of python console option to have it do this automatically. Does something liket this exist? Thanks!

like image 774
Jonathon Reinhart Avatar asked Jun 10 '11 14:06

Jonathon Reinhart


2 Answers

The regular Python interpreter will call sys.displayhook to do the actual displaying of expressions you enter. You can replace it with something that displays exactly what you want, but you have to keep in mind that it is called for all expressions the interactive interpreter wants to display:

>>> import sys
>>> 1
1
>>> "1"
'1'
>>> def display_as_hex(item):
...     if isinstance(item, (int, long)):
...         print hex(item)
...     else:
...         print repr(item)
...
>>> sys.displayhook = display_as_hex
>>> 1
0x1
>>> "1"
'1'

I suspect you'll quickly get tired of seeing all integers as hex, though, and switch to explicitly converting the ones you want to see as hex accordingly.

like image 76
Thomas Wouters Avatar answered Sep 25 '22 00:09

Thomas Wouters


Something like this, perhaps?

class HexInt(int):
    "Same as int, but __repr__() uses hex"

    def __repr__(self):
        return hex(self)

So you'd use that when creating all your integers that you want to be shown as hex values.

Example:

>>> a = HexInt(12345)
>>> b = HexInt(54321)
>>> a
0x3039
>>> b
0xd431
>>> c = HexInt(a + b)
>>> c
0x1046a

Note that if you wanted to skip the explicit creation of a new HexInt when doing arithmetic operations, you'd have to override the existing int versions of methods such as __add__(), __sub__(), etc., such that they'd return HexInts.

like image 43
JAB Avatar answered Sep 25 '22 00:09

JAB