How can I configure ipython to display integers in hex format?
Asked Answered
S

2

17

Here's the default behavior:

In [21]: 255
Out[21]: 255

And here's what I would like:

In [21]: 255
Out[21]: FF

Can I setup ipython to do that?

Sopping answered 20/2, 2013 at 10:4 Comment(3)
possible duplicate of this post.Weapon
Related: Python console default hex displayArmstead
Related question: When I am in the Python or IPython console, what is called when I am returned an output? - Stack OverflowCissiee
C
26

You can do this by registering a special display formatter for ints:

In [1]: formatter = get_ipython().display_formatter.formatters['text/plain']

In [2]: formatter.for_type(int, lambda n, p, cycle: p.text("%X" % n))
Out[2]: <function IPython.lib.pretty._repr_pprint>

In [3]: 1
Out[3]: 1

In [4]: 100
Out[4]: 64

In [5]: 255
Out[5]: FF

If you want this always-on, you can create a file in $(ipython locate profile)/startup/hexints.py with the first two lines (or as one to avoid any assignments):

get_ipython().display_formatter.formatters['text/plain'].for_type(int, lambda n, p, cycle: p.text("%X" % n))

which will be executed every time you start IPython.

Chapter answered 21/2, 2013 at 2:27 Comment(4)
Even better: print both representations! formatter.for_type(int, lambda n, p, cycle: p.text("%d (0x%X)" % (n,n)))Murex
This suggestion is awesome, will save me cumulative hours of typing hex(...) to get results in hex format.Zoosperm
What does cycle do in the lambda definition?Armstead
I tried removing cycle, got an error, and looked at the relevant source code. It seems it's irrelevant in this case, but has something to do with printing iterables.Armstead
A
5

Based on minrk's answer and rjb's answer on another question, I put this in my Python startup file:

def hexon_ipython():
  '''To print ints as hex, run hexon_ipython().
  To revert, run hexoff_ipython().
  '''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("0x%x" % n))


def hexoff_ipython():
  '''See documentation for hexon_ipython().'''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("%d" % n))


hexon = hexon_ipython
hexoff = hexoff_ipython

So I can use it like this:

In [1]: 15
Out[1]: 15

In [2]: hexon()

In [3]: 15
Out[3]: 0xf

In [4]: hexoff()

In [5]: 15
Out[5]: 15
Armstead answered 8/6, 2017 at 3:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.