# Python API

Python conventions, the exception hierarchy, and a map of the texform module.

https://texform.dev/api/python

The `texform` Python package exposes the parser, document model, transform engine, and serializer from one Rust core. Install it with `pip install texform`; see [Installation](/docs/installation) for supported Python versions and platforms. Methods and arguments use snake_case; the JavaScript binding uses camelCase. Both bindings share the parsing and transform core, but configuration interfaces and some exception types differ.

Structured data crosses the boundary as plain dicts, never custom wrapper classes: parse results, transform reports, diagnostics, and argspec results are all dicts, and option inputs are dicts too. The bundled type stubs (`texform/__init__.pyi`) describe those shapes as `TypedDict` types, so editors and type checkers see the exact keys. `Document` and `Node` are live handles into a Rust tree; a `SyntaxNode` is a plain dict snapshot.

Configuration is two-layered. A per-call `config=` argument must be a complete configuration class — `ParseConfig` or the phase-nested `TransformConfig` — and a dict there raises `ConfigError`. Partial adjustments go through keyword overlays instead (`parse(src, reject_unknown=True)`, `normalize(src, rewrite={"enabled": False})`), where nested values are plain dicts, not phase-config instances. The parse baseline is lenient.

The structured library exceptions derive from `TexformError`, so a single `except texform.TexformError` catches them: `ParseError` (an operation needed a complete tree but parsing produced none), `EditError` (an invalid edit), `ConfigError` (invalid construction input), and `TransformError` (a transform-engine failure). `Parser.parse` returns malformed-input diagnostics and a `document` that may be `None`; invalid configuration still raises `ConfigError`.

## Modules

### [Parser](https://texform.dev/api/python/parser.md)

- `Parser` (class): Turn LaTeX source into a parse result.
- `ParseConfig` (class): Complete parse configuration. The only accepted `config=` type for parse.
- `ParseOverrides` (typedDict): Keyword overlays for `parse`. Omitted keys keep the baseline.
- `ParseResult` (typedDict): The result of `Parser.parse`: an optional document plus diagnostics.
- `ParseDiagnostic` (typedDict): A single parse diagnostic emitted alongside a parse result.
- `ParseDiagnosticKind` (typeAlias): Category of a parse diagnostic, such as `"unknown-command"` or `"argument-validation"`.
- `Span` (typeAlias): Half-open UTF-8 byte range `{"start": int, "end": int}` into the source.
- `SyntaxNode` (typeAlias): Lossless parse snapshot as a plain dict. The tagged-union shape is documented on the TypeScript `SyntaxNode` type; Python keeps this alias unexpanded.
- `ContextItem` (typeAlias): A knowledge-injection item: a command, environment, or delimiter-control dict.
- `CommandItem` (typedDict): A custom command injected into parser knowledge.
- `EnvironmentItem` (typedDict): A custom environment injected into parser knowledge.
- `DelimiterItem` (typedDict): A custom delimiter control injected into parser knowledge.

### [KnowledgeBase](https://texform.dev/api/python/knowledge-base.md)

- `KnowledgeBase` (class): Immutable knowledge shared by parsers, engines, and documents.
- `CommandItem` (typedDict): A custom command injected into parser knowledge.
- `EnvironmentItem` (typedDict): A custom environment injected into parser knowledge.
- `DelimiterItem` (typedDict): A custom delimiter control injected into parser knowledge.

### [Document](https://texform.dev/api/python/document.md)

- `Document` (class): The editable document tree — the working format you read, edit, and output.
- `NodeSpanEntry` (typedDict): One entry mapping a node identifier to its source byte span.
- `TokenizedLatex` (typedDict): Serialized LaTeX and tokens produced by the same serializer traversal.
- `SerializationToken` (typedDict): One serialization fragment with UTF-8 byte offsets.
- `SerializationTokenKind` (typeAlias): Semantic category of one serialization fragment.
- `NodeTable` (typedDict): Preorder node columns. Row indices are local to this snapshot.
- `ArgumentTable` (typedDict): All argument slots, ordered by owner row and slot index.
- `ColumnarTree` (typedDict): Tree columns for bulk structural analysis with Arrow or DataFrame tools.

### [Node](https://texform.dev/api/python/node.md)

- `Node` (class): A read-only handle into a `Document` for navigation and reading.
- `NodeKind` (typeAlias): Node kind as reported by `Node.kind()`. Python uses PascalCase (`"Root"`, `"Command"`, `"ActiveSpace"`).
- `RuntimeContentMode` (typeAlias): Runtime content mode reported by the tree API: `"math"` or `"text"`.
- `ErrorParts` (typedDict): The decomposed content of an `Error` placeholder node.
- `GroupKindExplicit` (typedDict): A group written with explicit braces `{ ... }`.
- `GroupKindImplicit` (typedDict): A group with no surrounding braces, inferred from structure.
- `GroupKindDelimited` (typedDict): A group bounded by a delimiter pair, such as `\left( ... \right)`.
- `GroupKindInlineMath` (typedDict): A group introduced by inline math shift, such as `$ ... $` in text mode.
- `GroupKindRef` (typeAlias): The kind of a `Group` node: explicit, implicit, delimited, or inline-math.
- `DelimiterValue` (typeAlias): A delimiter string: a character, a backslash-prefixed control, or a dot.
- `MathArg` (typedDict): A command argument carrying math-mode content.
- `TextArg` (typedDict): A command argument carrying text-mode content.
- `DelimiterArg` (typedDict): A command argument that is a single delimiter token.
- `CSNameArg` (typedDict): A command argument that is a control-sequence name.
- `DimensionArg` (typedDict): A command argument that is a TeX dimension, such as `2pt`.
- `IntegerArg` (typedDict): A command argument that is an integer literal.
- `KeyValArg` (typedDict): A command argument that is a `key=value` list.
- `ColumnArg` (typedDict): A command argument that is a tabular column specification.
- `BooleanArg` (typedDict): A command argument that is a star flag, modeled as a boolean.
- `ArgRef` (typeAlias): A read command argument: one of the discriminated argument-value dicts.
- `ArgFormKind` (typeAlias)
- `NodeSlotKind` (typeAlias)
- `ArgForm` (typedDict)
- `OperatorNameArg` (typedDict)
- `Paired` (class): Immutable content and delimiter pair for an argspec Paired slot.
- `Arg` (typeAlias): Slot input: source written inside the slot, a detached content node, a star flag, absence, or an explicit `Paired` delimiter pair.
- `NodeSlot` (typedDict)

### [TransformEngine](https://texform.dev/api/python/transform-engine.md)

- `TransformEngine` (class): Normalize a formula into the canonical form selected by a profile.
- `TransformConfig` (class): Complete transform configuration, nested by pipeline phase.
- `RewriteConfig` (class): Complete Rewrite phase configuration.
- `LowerAttributesConfig` (class): Complete LowerAttributes phase configuration.
- `FinalizeAstConfig` (class): Complete FinalizeAst phase configuration.
- `FlattenGroupsConfig` (class): Complete FlattenGroups phase configuration.
- `NormalizeOverrides` (class): Flat parse+transform overlays for `normalize`.
- `TransformOverrides` (typedDict): Keyword overlays for `transform`.
- `RewriteOverrides` (typedDict): Keyword overlays for the Rewrite phase.
- `LowerAttributesOverrides` (typedDict): Keyword overlays for the LowerAttributes phase.
- `FinalizeAstOverrides` (typedDict): Keyword overlays for the FinalizeAst phase.
- `FlattenGroupsOverrides` (typedDict): Keyword overlays for the FlattenGroups phase.
- `NormalizeReportResult` (typedDict): Text plus the diagnostic report from one explicit normalize report call.
- `TransformReport` (typedDict): Diagnostic report for one explicit report call.
- `TransformWarning` (typedDict): An unknown input name whose arguments or scope cannot be guaranteed.
- `LowerAttributesReport` (typedDict): The LowerAttributes phase report.
- `AttributeStat` (typedDict): Activity for one `(attr, value)` pair in LowerAttributes.
- `AttributeFormCounts` (typedDict): Counts of one attribute form, split by carrier.
- `RewriteReport` (typedDict): The Rewrite phase report.
- `RewriteRuleStat` (typedDict): One rewrite rule's outcome for a single call.
- `FinalizeAstReport` (typedDict): The FinalizeAst phase report.
- `FlattenGroupsReport` (typedDict): The FlattenGroups phase report.
- `FlattenGroupsActionCounts` (typedDict): Flatten actions that changed the tree.
- `FlattenGroupsGuardCounts` (typedDict): Preserve-guard hits for one FlattenGroups run.
- `TransformProfile` (typeAlias): Normalization profile name: `"authoring"`, `"faithful"`, `"corpus"`, or `"equiv"`.

### [serialize](https://texform.dev/api/python/serialize.md)

- `serialize` (function): Render a `SyntaxNode` dict to LaTeX text.
- `SerializeOptions` (typedDict): Options for `Document.to_latex`, `Document.to_tokenized_latex`, and `serialize`.
- `Style` (typeAlias): Spaced output is byte-stable; compact preserves structure and text idempotency.

### [validate_argspec](https://texform.dev/api/python/validate-argspec.md)

- `validate_argspec` (function): Validate an xparse-style argspec string and report its parsed slots.
- `ValidateArgspecResult` (typedDict): The outcome of validating an argspec string with `validate_argspec`.
- `ParsedArgSpecSlot` (typedDict): One parsed argument slot of an xparse-style specification.
- `ArgSpecKindType` (typeAlias): Value kind of one parsed argspec slot (content, delimiter, star, ...).
- `ArgSpecFormType` (typeAlias): Surface form of one parsed argspec slot (mandatory, optional group, paired, ...).

### [Utilities](https://texform.dev/api/python/utilities.md)

- `list_packages` (function): List the built-in knowledge packages with their record counts.
- `count_targets` (function): Count command, environment, and character targets in a LaTeX formula.
- `PackageInfo` (typedDict): Summary of one built-in knowledge package.
- `TexformError` (exception): Base class for every exception the library raises.
- `ParseError` (exception): Raised when source could not be parsed into a complete tree.
- `EditError` (exception): Raised by a `Document` editing method on an invalid edit.
- `ConfigError` (exception): Raised on invalid construction or per-call configuration input.
- `TransformError` (exception): Raised on a transform-engine failure.
- `ConformanceError` (exception): Raised when a construction, edit, or syntax import violates the knowledge base or the document's structure.
- `list_rules` (function): List the built-in rewrite rules, sorted by key.
- `RuleInfo` (typedDict): Summary of one built-in rewrite rule.
- `RuleFidelity` (typeAlias): A rewrite rule's worst-case equivalence guarantee, least to most faithful: `"math"` (meaning preserved, rendering may change), `"reading"` (notation content, reading order, and structural roles preserved), or `"render"` (rendering equivalent under the reference renderer).
- `RuleLevel` (typeAlias): The first profile that accepts a rewrite rule's output as a suitable product.

