Custom Display for ObjA List

We can register a custom type for say numpy.polynomial.polynomial with the ipython mapping engine, as follows

ip = get_ipython() foramtter = ip.display_formatter.formatters['text/latex'] foramtter.for_type_by_name('numpy.polynomial.polynomial', 'Polynomial', display_func) 

I would like to use the .for_type_by_name (...) method to register a custom display for a list of a specific type, such as ObjA, and not just the ObjA type itself.

How can i do this?

Btw, I do not have access to the class that returns the ObjA list.

+5
source share
1 answer

How about creating formatting for list objects that will only act when it sees a list of ObjA objects?

 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) 

It seems that if the formatting function returns None , the formatter is ignored. At least this works for me:

 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 

This is a rather dirty hack, but, unfortunately, I see no other way (besides fixing the DisplayFormatter monkey, which is even more dirty, although it should be more powerful). If there is, I hope someone enlightens us.

0
source

All Articles