Python API reference
Reference for the mathconv Python package: the convert function, the Converter class, results, fallbacks, errors and threading.
The package exports four names: the function convert and the classes
Converter, Result and Fallback. It ships type stubs, so type
checkers and editors see the signatures below.
Functions#
mathconv.convert(text, source="mathml", target="latex", **options) -> str
Converts one formula and returns the output as a string. source names
the source format and target the target format; the keyword
arguments are the options of those formats, as listed in
Conversion options. Each call checks the formats and
options again, so code that converts many formulas with the same
settings is better served by a Converter.
import mathconv
mathconv.convert("<math><msup><mi>x</mi><mn>2</mn></msup></math>")
# 'x^2'
mathconv.convert("<math><mfrac><mn>1</mn><mi>x</mi></mfrac></math>", target="text")
# '1/x'
mathconv.convert("<math><mi>x</mi></math>", delimiters="paren")
# '\\(x\\)'
Converter#
converter = mathconv.Converter(source="mathml", target="latex", **options)
converter.convert(text) -> str
converter.result(text) -> mathconv.Result
converter.convert_batch(texts) -> list[str]
converter.result_batch(texts) -> list[mathconv.Result]
A converter holds a source format, a target format and their options. The constructor checks them once, and every call then converts with them. Converters are immutable and can be shared between threads. They cannot be pickled; a worker process creates its own.
convertconverts one formula and returns the output.resultconverts one formula and returns aResult.convert_batchconverts formulas and returns their outputs.result_batchconverts formulas and returns theirResultobjects.
The batch methods take any iterable of str, such as a list, a tuple
or a generator, and return a list with one entry per input, in input
order. The formulas are converted independently, so broken markup in
one formula affects only that formula's result.
import mathconv
converter = mathconv.Converter(target="text")
converter.convert_batch(["<math><mi>a</mi></math>", "<math><msqrt><mi>b</mi></msqrt></math>"])
# ['a', 'sqrt(b)']
converter.convert_batch(formula for formula in [])
# []
Input#
Each input is a str holding one formula. To convert bytes, decode
them first, as in data.decode("utf-8").
mathconv converts the first math element of the input and ignores
everything before and after it. Further math elements after the
first are not converted, and the fallback extra-math records how many
there are. Input with no math element gives empty output and the
fallback no-math:
import mathconv
converter = mathconv.Converter()
result = converter.result("<math><mi>a</mi></math><math><mi>b</mi></math>")
result.output, [(fallback.code, fallback.detail) for fallback in result.fallbacks]
# ('a', [('extra-math', '1')])
result = converter.result("a plain sentence")
result.output, [fallback.code for fallback in result.fallbacks]
# ('', ['no-math'])
Supported MathML describes which markup is converted.
Result#
mathconv.Result is the result of one conversion. It has these
read-only attributes:
| Attribute | Type | Value |
|---|---|---|
output | str | the formula in the target format |
display | bool | True for a display formula, False for an inline formula |
taken_from | str | "markup" for converted markup; "annotation" or "alttext" for carried TeX |
fallbacks | list[mathconv.Fallback] | every fallback, in input order; empty for carried TeX |
A formula is a display formula when its math element has
display="block", or mode="display" in markup written for MathML 1.
Using the LaTeX output
explains how to render each kind. Carried TeX is LaTeX that the
markup carries alongside the formula, which the option
prefer_carried_tex returns instead
of the converted markup.
Results are created only by conversions, and they compare by identity:
compare their attributes to compare two results. Their repr shows the
attributes, with the fallbacks by code:
import mathconv
result = mathconv.Converter().result("<math><mi>x</mi><menclose notation='circle'><mn>1</mn></menclose></math>")
repr(result)
# 'Result(output="x1", display=False, taken_from="markup", fallbacks=["unsupported-notation"])'
Fallback#
mathconv.Fallback describes one part of the input that was not
converted. It has two read-only str attributes: code, which names
the kind of fallback, and detail, which names the element, entity,
character or notation concerned, such as mstack or &foo;.
import mathconv
result = mathconv.Converter().result("<math><mi>x</mi><mo>&foo;</mo></math>")
result.fallbacks[0].code, result.fallbacks[0].detail
# ('unknown-entity', '&foo;')
The codes and what the output holds for each are listed under Fallbacks.
Errors#
Creating a converter, or calling mathconv.convert, with an unknown
format, option or option value, or with an option that does not
belong to the chosen formats, raises ValueError. An option value of
the wrong type, such as drop_labels=1, raises TypeError. The
message names the problem:
import mathconv
try:
mathconv.Converter(target="text", delimiters="dollar")
except ValueError as error:
message = str(error)
message
# 'the option `delimiters` does not belong to the chosen formats'
An input that is not a str raises TypeError, and so does a single
str passed to a batch method, which takes an iterable of strings. A
batch with any item that is not a str raises TypeError and returns
no results. Nothing else raises: broken or unsupported markup is
reported through fallbacks.
Threads and the GIL#
CPython runs Python code under the GIL (global interpreter lock), so only one thread executes Python code at a time. Native extensions such as mathconv can release the GIL while they work.
Single-formula calls (convert and result) hold the GIL, because one
conversion takes less time than releasing and reacquiring it. A batch
call collects its inputs, releases the GIL, converts the formulas one
after another on the calling thread, and reacquires the GIL to build
the results, so other Python threads run in the meantime. It reads each
str in place rather than copying it. A batch call uses one core; to
use several, call the batch methods from several threads or processes,
as Performance shows.
Rust#
The conversion engine is the Rust crate mathconv in the
repository. It is not
published on crates.io, and the Python package is its supported
interface. Architecture
describes the crate's interface for contributors.