Python console default hex display
Solution 1:
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.
Solution 2:
Building on previous answers, here's a version that works for Python 2/3, doesn't display bools as hex, and also properly sets the _
variable:
import sys
def _displayhook(o):
if type(o).__name__ in ('int', 'long'):
print(hex(o))
__builtins__._ = o
else:
sys.__displayhook__(o)
def hexon():
sys.displayhook = _displayhook
def hexoff():
sys.displayhook=sys.__displayhook__
Solution 3:
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 HexInt
s.
Solution 4:
Modifying the top python2 answer for python3...
def display_as_hex(item):
if isinstance(item, int):
print(hex(item))
else:
print(repr(item))
import sys
sys.displayhook = display_as_hex