How to Elegantly Write LaTeX with Python?

terry 30/11/2025

LaTeX is a typesetting system based on ΤΕΧ, exceptionally good at displaying complex mathematical formulas. latexify is a Python library that generates LaTeX mathematical expressions. This project can easily generate descriptions of complex LaTeX mathematical formulas using Python functions.

《How to Elegantly Write LaTeX with Python?》

1. Installing the Library

bash

pip install latexify-py
《How to Elegantly Write LaTeX with Python?》

Check the version number:

python

import math  # Optional
import numpy as np # Optional
import latexify

latexify.__version__

Output:

text

'0.4.2'

2. Example Demonstration

We need to use it in the form of a decorator. Let’s take the quadratic formula as an example:

Without the decorator:

python

def solve(a, b, c):
  return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

print(solve(1, 4, 3))
print(solve)

Output:

text

-1.0
<function solve at 0x1124f28e0>

Using the decorator:

python

@latexify.function
def solve(a, b, c):
  return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

print(solve(1, 4, 3)) 
print(solve) 

Output:

text

-1.0
\mathrm{solve}(a, b, c) = \frac{-b + \sqrt{ b^{2} - 4 a c }}{2 a}

View the solve function separately:

python

solve
《How to Elegantly Write LaTeX with Python?》

You can also use the @latexify.expression decorator directly for different formatting.

《How to Elegantly Write LaTeX with Python?》

Other example effects:

《How to Elegantly Write LaTeX with Python?》
《How to Elegantly Write LaTeX with Python?》
《How to Elegantly Write LaTeX with Python?》

3. Further Information

For more information, you can refer to the source project:
https://github.com/google/latexify_py