Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

ipython

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?

like image 234
geschema Avatar asked Feb 20 '13 10:02

geschema


2 Answers

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.

like image 147
minrk Avatar answered Sep 19 '22 02:09

minrk


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
like image 24
wjandrea Avatar answered Sep 18 '22 02:09

wjandrea