leptris (Python) — lxml-shaped bindings for libleptris
leptris wraps the libleptris
C API (XML 1.0 parsing, XPath 1.0) using cffi in ABI mode, with a
required C accelerator for Element allocation and the hot accessors
(tag, text, attrib, get, indexing, sibling navigation and
plain-path XPath evaluation). Wheels ship it compiled; sdist builds
require a C compiler.
The pinned libleptris version lives in libleptris-version.txt
(lockstep releases); CI builds it from the release tarball.
Platform wheels bundle the compiled engine — pip install leptris works with no extra setup on macOS (x86_64/arm64), Linux
(manylinux + musllinux, x86_64/aarch64) and Windows (amd64/arm64).
Requirements
Python 3.9+
cffi (installed automatically)
nothing else for wheel installs — the pinned libleptris is
vendored into leptris/_vendor/ by the wheel build
(scripts/vendor_libleptris.sh). Wheels carry the compiled
library AND its exact source (_vendor/engine/, with rebuild
instructions in _vendor/README.md)
source installs (pip install --no-binary leptris) need a C
toolchain + cmake; the sdist bundles the pinned engine source
and compiles it at install time — no LEPTRIS_LIB_PATH
Supported runtimes
CPython 3.9+ (abi3 wheels; one wheel per platform covers every
supported CPython, including future 3.x releases)
Free-threaded CPython (3.13t/3.14t): supported — cp314t wheels
ship for every platform, built with Py_GIL_DISABLED (version-
specific; the accelerator's Fns table is write-once at import).
Contract: one document per thread (documents may migrate
between threads between calls); the shared SAX recorder is
internally serialized
PyPy / GraalPy: unsupported — the accelerator is required
(single-mode by design); a pure-cffi fallback would contradict
the binding's purpose. Revisit only on real demand.
Wheel platforms
Every release ships a universal wheel per platform (abi3, covering
all CPython 3.9+) plus the matching free-threaded cp314t wheel and
a source distribution. Each wheel runs the full test suite on its
platform as part of the release build.
Platform
Wheels
Notes
Linux x86_64 (glibc ≥ 2.17)
abi3 + cp314t
manylinux
Linux x86_64 (musl)
abi3 + cp314t
musllinux (Alpine)
Linux aarch64 (glibc / musl)
abi3 + cp314t
native runners
Linux ppc64le
abi3
full suite under qemu
Linux s390x
abi3
big-endian; full suite under qemu
Linux riscv64
abi3
full suite under qemu (glibc + musl)
Linux i686 (glibc + musl)
abi3
full suite (musl under qemu)
Linux armv7l (glibc + musl)
abi3
full suite under qemu
macOS x86_64 + arm64
abi3 + cp314t
universal2; x86_64 slice Rosetta-tested
Windows x64 + ARM64
abi3 + cp314t
suite runs on both architectures
Windows x86 (32-bit)
abi3
first wheel in 1.9.280.0 (engine #1456)
Every leg is required: a red leg fails the release before publish.
For a development checkout (or to use your own libleptris
build), the loader also accepts a shared library
(libleptris.dylib / .so / .dll) on the loader path, or one
named by LEPTRIS_LIB_PATH (which must name the library
file — the loader dlopens it verbatim; it takes precedence
over the vendored copy):
Documents own the tree; use the context manager or close():
from leptris import parse
with parse("catalog.xml") as doc:
doc.xpath("//book[@lang='en']")
Namespaces, variables, canonical XML and streaming:
root.xpath("//x:item", namespaces={"x": "urn:ex"})
root.xpath("//book[@id=$id]", variables={"id": "2"})
c14n(root, exclusive=True)
from leptris import sax
sax.parse(xml, handler) # one-shot
with sax.StreamingParser(handler) as parser: # push, constant memory
parser.feed(chunk, final=last)
for rec in sax.records(xml): # one-crossing records tape
... # (leptris 1.9.237.1+)
XSLT and XPath version support
leptris.XSLT(stylesheet) compiles once, applies to any Document, and
returns a Document; leptris.XPath(expression) compiles an XPath for
repeated evaluation. Which language constructs work is decided by the
engine — the matrix below is measured against libleptris 1.9.32
(audited through this binding; the upstream gap ledger is
leptris/leptris#685).
language
status
notes
XSLT 1.0
full
libxslt conformance suite 205/205 upstream; EXSLT math/set/str/date included
Compile a descriptor once, materialize whole documents in one native
pass — the tree-shaped ABI lutaml-model hosts consume (leptris/leptris#1039):
from leptris import Document, Plan
catalog = Plan({
"element_name": "catalog",
"children": [
{"name": "item", "kind": "collection", "plan": {
"element_name": "item",
"attributes": {"id": {}, "price": {}},
"children": [{"name": "title"}],
}},
{"name": "note", "kind": "raw"},
],
})
with Document.parse(xml) as doc:
data = catalog(doc) # {"attributes": {...}, "children": {...}}
Row kinds: scalar, collection (list), nested (element plan),
raw (serialized subtree), content (mixed-content text runs, name
may be ""), callback (PlanCallback(value, position, type_tag)
— the escape hatch for host-side procs). Results are shape-stable
(absent rows yield None / []); namespace forms via
ns={"form": "none"|"exact"|"any", "uri": ...}, flags via
{"mixed_content", "ordered", "cdata", "ns_lenient"}.
Serialize a walk (serialize) or a host-assembled flat op program
(serialize_ops) back to XML; indent/indent_unit pretty-print
element boundaries (1.9.341+, #425). document_ops(ops) and
to_document(element_or_document) materialize the same results as
native Document trees — attributes verbatim, root namespace
declarations riding as xmlns attributes — with no string round
trip (1.9.341+, #426):
The default surface is the full XPath 3.1 grammar. To pin the
strict XPath 1.0 surface (3.x-only syntax raises XPathError),
pass version="1.0" — on Document.xpath, Element.xpath, and
the compiled XPath class (XPath(expr, version="1.0")):
Unsupported constructs fail at XSLT() compile time or at evaluation
with LeptrisError — except two instructions that still produce
empty output instead of an error (xsl:map/xsl:map-entry, and
xsl:value-of/@separator is ignored); tracked in the
#685/#690 ledgers above.
HTML parsing
leptris.html (libleptris 1.9.75+) — tolerant HTML in the shape of
lxml's etree.HTMLParser: implied end tags, void elements,
case-insensitive names, unquoted attributes, the named-entity
table, and a synthesized <html>/<head>/<body> wrapper:
from leptris import html
r = html.fromstring("<p>hello <b>world") # <html><head/><body><p>hello <b>world</b></p></body></html>
with html.document("<td>c") as doc:
doc.xpath("count(//td)") # 1.0
Since libleptris 1.9.76 the output is byte-exact with lxml's
etree.HTMLParser (minimized attributes are empty strings; no
empty <head/> is emitted) — leptris/leptris#813. The one
deliberate html4 divergence: a leading script/style run
stays in body (the fragment shape), where lxml's libxml2 lifts
it to head.
Two modes (libleptris 1.9.104+): the default html4 keeps this
compatibility shape; mode="whatwg" selects the WHATWG-conformant
engine — with libleptris 1.9.196 the WHATWG conformance corpus is
at zero divergences (leptris/leptris#659 complete): tree
construction, foster parenting, adoption agency, in-select/table
scope, and the foreign-content rules all match the specification.
leptris fully provides HTML.
Building HTML works like building XML, on an HTML-mode document —
serialization emits void elements without closing tags and keeps
<br>-style names un-XHTML-ed (libleptris 1.9.225+):
from leptris import html
import io
doc = html.create()
p = doc.create_element("p", {"class": "intro"})
doc.set_root(p)
p.text = "hello"
buf = io.BytesIO(); doc.save_html(buf) # <p class="intro">hello</p>
tostring(node, method="html") forces HTML output for any tree;
HTML-parsed and html.create() documents serialize as HTML by
default.
Migrating from lxml
lxml
leptris
Notes
etree.fromstring / etree.XML
fromstring / XML
etree.parse
parse
paths and file-likes; no URLs
etree.tostring(elem, …)
tostring(elem, …)
bytes by default, encoding="unicode" for str
elem.tag / .text / .tail
same
tag uses {uri}local Clark notation; CDATA merges into text (lxml's default parser behavior)
elem.attrib / .get() / .keys() / .items()
same
attrib is a read-only Mapping
elem.getparent/getnext/getprevious
same
elem[i], len(elem), iteration, slices
same
indexing is child indexing, never attribute lookup
elem.iter() / .iterdescendants() / .itertext()
same
elements only (ElementTree semantics); lxml's iter() also yields comments/PIs
elem.find/findall/findtext
same
accepts full XPath 1.0 — a superset of ElementPath — including {uri}local names
Document.create() + create_element(name) + set_root() (returns the installed element; foreign parentless elements adopt by copy, 1.9.298+), Element.create_child(name)/append(el)/set(name, value) + the .text setter — libleptris 1.9.216+; remove via Document.remove_* (doctype/child)
document-level comments / PIs
doc.toplevel_comments() / doc.toplevel_pis()
prolog then epilog; requires libleptris 1.9.3+
etree.iterparse
leptris.iterparse(source, full_document=False)
bounded by the largest subtree; yields ("end", element); elements borrowed until the next yield; tags resolve namespaces (Clark notation, libleptris 1.9.4+). Truncated or malformed input raises ParseError (both modes, libleptris 1.9.15+). full_document=True yields every element in completion order. Perf opt-outs: skip_dup_detection=True / skip_source_positions=True (libleptris 1.9.284+, ~48% faster on diagnostics-free streams)
smart strings
plain str
XPath string/attribute results
elem.nsmap
absent
use elem.namespace / elem.prefix and xpath(namespaces=…)
etree.XPath compiled objects
leptris.XPath(expression)
compile once, evaluate many; contexts, namespaces, and variables supported
etree.XSLT
leptris.XSLT(stylesheet)
compile once, apply to any Document — see the version support matrix above; apply-time top-level params: transform(doc, params={"n": "//v"}) (XPath-expression values, libleptris 1.9.287+) or string_params for the serialized result
elem.sourceline
same
requires libleptris 1.3.0+
undeclared XPath prefix
raises in lxml
evaluates to an empty nodeset here
ATTLIST default attributes
applied by lxml's default parser
excluded by default (ElementTree-like; XML 1.0 §5 permits either) — Document.parse(xml, attribute_defaults=True) opts in
declared non-UTF-8 bytes (UTF-16, latin-1, …)
auto-detected
auto-detected — declared encodings route through the converter, others retry on failure (libleptris 1.9.15+)
parser options (remove_blank_text, …)
etree.XMLParser(remove_blank_text=True)
Document.parse(xml, remove_blank_text=True) — ~35% faster on pretty-printed input; also attribute_defaults=True, recover=True (XML_PARSE_RECOVER parity — structural errors keep the best-effort tree with per-recovery diagnostics on Document.parse_diagnostics, 1.9.344+), and the perf opt-outs skip_dup_detection=True / skip_source_positions=True (1.9.273+, ~13% faster on diagnostics-free workloads); the streaming twins on iterparse/sax.parse/StreamingParser (1.9.284+, ~48% on streams)
elem.attribute_pairs() — all attributes as (name, value) pairs in one C pass (1.9.216+)
typed attribute read
—
elem.get_int/get_float/get_bool(name, default) — conversion engine-side, one crossing (1.9.280.1+); strict: unparseable or missing -> default
bulk attribute read (ns)
—
elem.attribute_pairs(ns=True) — (name, value, prefix, uri) 4-tuples in one crossing; URI resolved through in-scope declarations, reserved xml: binding included (1.9.353+)
subtree walk
elem.iter()
elem.visit_entering(fn) — one callback per node entered, document order, no re-visit after the subtree (1.9.232+)
host-assembled results
—
Plan.serialize_ops(ops) — serialize a flat op program (element/attr/scalar/end tuples) guided by the plan, no DOM needed (1.9.334+); indent/indent_unit pretty-print (1.9.341+)
result -> native tree
—
Plan.document_ops(ops) / Plan.to_document(doc) — build a Document from an op program or a walk, attributes verbatim, xmlns declarations on the root, no string round trip (1.9.341+)
catch-all child rows
—
plan child rows take {"kind": "wildcard"} — the unbound remainder as RAW subtrees (or walked via a nested "plan"); Plan.serialize(doc) serializes a walk back to XML with ns_prefix declarations (1.9.312+)
content digest
—
elem.digest([drop_whitespace][, attr_order]) — Merkle hash of the subtree; stable across processes (attr_order: 1.9.208+)
Layout
leptris/_ffi.py — cdef mirror of the public headers + loader
(the only place libleptris is declared)
leptris/_engine.py — the compile-once lifecycle base shared by
the compiled language objects (XSLT, XQuery, future RelaxNG)
leptris/_results.py — the result model: engine results to
Python values (nodeset wrapping, scalar conversion), shared by
every evaluation surface
leptris/_leptrisaccel.c — the C accelerator (abi3): allocates
Elements and runs the hot accessors, subtree iteration, the parse
and serialization seams, and the per-document element registry;
bound to libleptris by the positional protocol in element.py
leptris/element.py, document.py, node.py, xpath.py —
the Python surface: queries, walks, documents; node.py exposes
the full DOM (comments, CDATA, PIs) beneath the ElementTree shape
tests/ — pytest suite (pytest with LEPTRIS_LIB_PATH set)
benchmarks/ — matrix vs lxml/ElementTree/minidom (pip install .[bench], then python -m benchmarks.matrix)
Memory model
The Document owns the whole tree and its pool. Accessor strings
are copied into Python str at the boundary, so nothing depends on
document lifetime after a call returns. Elements keep a reference to
their Document, so the pool cannot be freed while any wrapper is
alive. Prefer explicit close() / the context manager; __del__ is
a refcounting safety net, not a contract. Using an element after its
document is closed raises LeptrisError.
Versioning
libleptris-version.txt pins the library release the binding is
built and tested against. Since 1.9.76.0 the package version is
{c-full-semver}.{patch} — the pinned libleptris version plus
a binding-local patch counter: lib 1.9.76 → 1.9.76.0, then
1.9.76.1 for binding-only fixes against the same pin, resetting
the patch whenever the pin moves. (1.2.0–1.27.1 were the interim
own-semver line.) pyproject.toml and leptris/__init__.py must
agree at release time.
Publishing
Releases publish to PyPI via .github/workflows/release.yml, using
PyPI trusted publishing (no stored credentials). The workflow
runs on manual dispatch (ships the version in pyproject.toml) and
is called by the libleptris release flow (publish: true), so every
libleptris release ships the wheel.