Skip to main content

Convert a Python expression string to a KaTeX string

Project description

expr2katex

Convert a Python expression string to a KaTeX string.

from expr2katex import expr2katex

katex, err = expr2katex("sin(a) + (c + 3) * b")
# katex → \sin\left(a\right)+\left(c+3\right)\times b
# err   → None

Features

  • Zero dependencies — built on Python's standard ast module only
  • Precedence-aware parenthesisation — reconstructs grouping from the AST structure, so (a + b) * c renders correctly without any string heuristics
  • KaTeX-native functionssin, cos, sqrt, log, etc. render with their native KaTeX commands (\sin, \sqrt{x}, …)
  • Unknown functions fall back to \operatorname{foo} automatically
  • Configurable division style\frac{a}{b} or a \div b
  • Symbol style overrides — control how variables and function names are rendered per symbol
  • SyntaxError highlighting — invalid expressions return a KaTeX string with the offending token highlighted in red, designed for real-time UI previews

Installation

pip install expr2katex

Usage

Basic

from expr2katex import expr2katex

katex, err = expr2katex("sin(a) + b * c")
# \sin\left(a\right)+b\times c

Division style

expr2katex("a / b")                      # \frac{a}{b}  (default)
expr2katex("a / b", div_style="div")     # a \div b

Power and roots

expr2katex("a ** 2")          # a^{2}
expr2katex("sqrt(x)")         # \sqrt{x}
expr2katex("sqrt(x, 3)")      # \sqrt[3]{x}   (n-th root)

Symbol style overrides

from expr2katex import expr2katex, SymbolStyle

expr2katex("foo(x)", symbol_styles={
    "foo": SymbolStyle.TEXT,       # \text{foo}\left(x\right)
    "x":   SymbolStyle.BOLD,       # \boldsymbol{x}
})
SymbolStyle Output Default for
ITALIC x variables
OPERATORNAME \operatorname{foo} functions
TEXT \text{foo}
BOLD \boldsymbol{x}

SyntaxError highlighting

When the expression is invalid, expr2katex returns a KaTeX string with the offending token highlighted in red — useful for real-time formula editors.

katex, err = expr2katex("sin(a + (b * c")
# katex → \text{sin(a + }\textcolor{red}{\underbrace{\text{(}}}\text{b * c}
# err   → '(' was never closed

Choose between underbrace (default) and underline:

expr2katex("sin(a + (b * c", error_style="underline")

Raising on error

# SyntaxError is re-raised instead of being returned
expr2katex("sin(a + (b * c", raise_on_error=True)
# SyntaxError: '(' was never closed

# All non-SyntaxError exceptions are always raised regardless of raise_on_error.

API reference

def expr2katex(
    expr: str,
    raise_on_error: bool = False,
    div_style: Literal["frac", "div"] = "frac",
    symbol_styles: dict[str, SymbolStyle] | None = None,
    error_style: Literal["underbrace", "underline"] = "underbrace",
) -> tuple[str, str | None]: ...
Parameter Type Default Description
expr str Python expression string to convert
raise_on_error bool False Re-raise SyntaxError instead of returning highlighted KaTeX
div_style "frac" | "div" "frac" Division rendering style
symbol_styles dict[str, SymbolStyle] | None None Per-symbol style overrides
error_style "underbrace" | "underline" "underbrace" Error highlight decoration

Returns (katex: str, err: str | None)err is None on success, or SyntaxError.msg on failure.

Supported operators

Python KaTeX output
+ a+b
- a-b
* a\times b
/ \frac{a}{b}
// \lfloor\frac{a}{b}\rfloor
% a\bmod b
** a^{b}
-x -x
+x x (omitted)

KaTeX-native functions

The following function names are rendered with their native KaTeX command (\sin, \cos, …). All other names fall back to \operatorname{name}.

sin cos tan arcsin arccos arctan sinh cosh tanh log ln exp min max gcd lcm det dim sqrt

sqrt uses the dedicated \sqrt{x} template. Pass a second argument for n-th roots: sqrt(x, n)\sqrt[n]{x}.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

expr2katex-0.1.0.tar.gz (8.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

expr2katex-0.1.0-py3-none-any.whl (7.9 kB view details)

Uploaded Python 3

File details

Details for the file expr2katex-0.1.0.tar.gz.

File metadata

  • Download URL: expr2katex-0.1.0.tar.gz
  • Upload date:
  • Size: 8.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.16.5 cpython/3.13.12 HTTPX/0.28.1

File hashes

Hashes for expr2katex-0.1.0.tar.gz
Algorithm Hash digest
SHA256 c5a2c43714b916e9e127abd3dd767ce0d72a0a74968cb19d837d3e972950e474
MD5 edeaf1dc92918780cbfa29374559d566
BLAKE2b-256 e907c8c5325b28db1f981c55acdab811bdffe43798987d0afb8c0888c14c0afd

See more details on using hashes here.

File details

Details for the file expr2katex-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: expr2katex-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: Hatch/1.16.5 cpython/3.13.12 HTTPX/0.28.1

File hashes

Hashes for expr2katex-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 eb2500659f1e0395cece83fa81a7246367fd2bece093504868851a7feb77e125
MD5 ee5221b655961f645ba25aeb4f2905b1
BLAKE2b-256 7a5fa13e0b34a45ab6c452f3696c42c8070ab2d3b10cd60c383afd3ea97023e8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page