Как настроить ipython для отображения целых чисел в шестнадцатеричном формате?

Здесь поведение по умолчанию:

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

И вот что мне хотелось бы:

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

Могу ли я настроить ipython для этого?

Ответ 1

Вы можете сделать это, зарегистрировав специальный формат отображения для 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

Если вы хотите, чтобы это всегда было включено, вы можете создать файл в $(ipython locate profile)/startup/hexints.py с помощью первых двух строк (или как один, чтобы избежать любых назначений):

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

который будет выполняться каждый раз при запуске IPython.

Ответ 2

На основе ответа minrk и rjb answer по другому вопросу я поместил это в свой файл запуска Python

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

Поэтому я могу использовать его следующим образом:

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

In [2]: hexon()

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

In [4]: hexoff()

In [5]: 15
Out[5]: 15