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

I asked this question first on stackoverflow, they rightfully recommended me to ask it here, this is it

If we put these 3 lines in a jupyter notebook and run them, we get a nicely formatted equation with a MathJax/Latex format, which is nice.

import sympy

a, b, c = sympy.symbols('a b c')
(- b - sympy.sqrt(b**2 - 4*a*c)) / (2*a)


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,
"output_type": "execute_result"
}
],
"source": [
"import sympy\n",
"\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. another stackoverflow page), I would like to make a custom object behave as a sympy one, and 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

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:

4 Likes

Thank you so much for this perfect answer and the link to the documentation!

1 Like