【问题标题】:Custom Display Output for List of ObjAObjA 列表的自定义显示输出
【发布时间】:2015-08-12 09:54:41
【问题描述】:

我们可以使用 ipython 显示引擎为 numpy.polynomial.polynomial 注册一个自定义类型,如下所示

ip = get_ipython()

foramtter = ip.display_formatter.formatters['text/latex']

foramtter.for_type_by_name('numpy.polynomial.polynomial',
                             'Polynomial', display_func)

我想使用 .for_type_by_name(...) 方法为特定类型的列表注册自定义显示,例如 ObjA 而不仅仅是类型 ObjA 本身。

我该怎么做?

顺便说一句,我无权访问返回 ObjA 列表的类。

【问题讨论】:

  • 您可能想要添加一个 python 标签并提供更多详细信息。
  • Hmm... 再次考虑这个问题,我相信通过创建像Sage does this 这样的自定义格式化程序并替换text/plain 必须有一种更清洁的方法。抱歉,目前没有时间尝试使用正在工作的 sn-p。

标签: python ipython


【解决方案1】:

如何为list 对象创建一个仅在看到 ObjA 列表时才起作用的格式化程序?

from decimal import Decimal   # Decimal is my ObjA here

ip = get_ipython()
formatter = ip.display_formatter.formatters['text/latex']

def format_list(obj):
    if not isinstance(obj, list):
        return None
    if not all(isinstance(item, Decimal) for item in obj):
        return None
    return "$$[%s]$$" % ";".join(map(str, obj))

formatter.for_type_by_name('builtins', 'list', format_list)

似乎如果格式化函数返回None,格式化程序将被忽略。至少它对我有用:

In[2]: [Decimal("1"), Decimal("2"), "not a decimal"]
Out[2]: [Decimal("1"), Decimal("2"), "not a decimal"]

In[3]: [Decimal("1"), Decimal("2")]
Out[3] 1, 2  # LaTeX-formatted, yeah

这是一个非常肮脏的 hack,但不幸的是我没有看到任何其他方式(除了猴子修补 DisplayFormatter,它甚至更脏,虽然它应该更强大)。如果有,希望有人能不吝赐教。

【讨论】:

  • 在更新的 IPython 版本中,这不再起作用了,看我的回答 here
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多