how to write a class which naturally produce a latex output in jupyter notebook

Question:

This question is not a duplicate of this one, even if it is closely related.

When I use sympy on a jupyter notebook, it nicely format the output of my equations with MathJax, like this:

sympy latex output demonstration

If we have a look at the source of the notebook, we can see that the output saved is made of two parts text/plain and text/latex :

"outputs": [
 {
  "data": {
   "text/latex": [
    "$\displaystyle \frac{- b - \sqrt{- 4 a c + b^{2}}}{2 a}$"
   ],
   "text/plain": [
    "(-b - sqrt(-4*a*c + b**2))/(2*a)"
   ]
  },
  "execution_count": 22,
  "metadata": {},
  "output_type": "execute_result"
 }
],
"source": [
 "import sympyn",
 "n",
 "a, b, c = sympy.symbols('a b c')n",
 "(-b - sympy.sqrt(b**2 - 4*a*c)) / (2*a)"
]

Even if I know how to print in a latex form (cf. link above), I would like to make a custom object behave as a sympy one, and be able to be displayed naturally as latex math in a jupyter notebook (and if I could fill both the text/latex and text/plain fields it would be nice !). If anyone had a clue on how to do it 🙂

Asked By: yota

||

Answers:

I asked the forum and got a fast answer (link), as promised, I copy/paste it here (all credits goes to bollwyvl):

The key resource for the plumbing is in the Integrating your objects with IPython section of the docs.

Here’s an example:

class Foo:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def _repr_mimebundle_(self, **kwargs):
        return {
            "text/plain": f"x={self.x}",
            "text/latex": f"$x = {self.x}\\y = {self.y}$"
        }

foo = Foo(1, 2)
foo

yields:

enter image description here

Answered By: yota
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.