pyxsd.xslt

XSLT 3.0 compilation, invocation, and optional advisory inspection.

The normative processor, compiled stylesheet, and result views are the public entry points. inspect_stylesheet() provides a separate, non-normative binding of the packaged XSLT schemas; it never decides acceptance or compiles the stylesheet.

Submodules

Attributes

Exceptions

XsltDynamicError

A dynamic error raised while executing a transformation.

XsltInspectionError

Advisory stylesheet inspection could not read or bind its inputs.

XsltInvocationError

An invalid host invocation option combination.

ResultShapeError

The requested result view does not have the required shape.

Classes

ExtensionInstruction

One registered application instruction and its executor.

ExtensionSignature

Declared parameter and result sequence types for one extension.

XsltExtensions

An immutable registry of extension functions, instructions, collations.

InspectionDiagnostic

One classified, advisory inspection finding.

StylesheetInspection

The result of advisory stylesheet inspection.

OutputPolicy

Authorize one absolute output URI before its content is constructed.

CompiledStylesheet

One immutable compiled stylesheet or package.

XsltProcessor

Immutable processor identity and resource configuration.

PythonRuleContext

The restricted dynamic context passed to every Python rule callback.

PythonRules

An immutable set of Python component overrides and mode rules.

Message

One stylesheet message or diagnostic event.

ResultEntry

One principal or secondary result in every available view.

TransformationResult

The principal and secondary results of one transformation.

ExecutionLimits

Explicit budgets for one transformation and its nested invocations.

Functions

inspect_stylesheet(source, *[, language, resource_policy])

Bind one stylesheet module as an advisory, non-normative structural view.

Package Contents

exception pyxsd.xslt.XsltDynamicError(message, *, code=None, phase='dynamic', uri=None, module=None, package=None, location=None, stack=(), cause=None, allow_catch=True, description=None, has_description=True, value=(), line_number=None, column_number=None)

A dynamic error raised while executing a transformation.

code is normally an XSLT XTDE/XTTE code or an XPath error code. The execution runtime’s own resource limits use the stable implementation code PYXSD-XSLT-001; callers can test it exactly without depending on message text. allow_catch is false for foreign callback failures that crossed an XSLT boundary without being deliberately converted.

Parameters:
allow_catch = True
property catchable: bool

Whether a coded xsl:catch may consume this error.

Only dynamically signaled XSLT/XPath errors are catchable. Static and serialization errors are outside xsl:try, and a foreign callback failure is not converted merely because it crossed an XSLT boundary.

Return type:

bool

exception pyxsd.xslt.XsltInspectionError

Advisory stylesheet inspection could not read or bind its inputs.

This is an input/resource failure, not an XSLT static error. Schema legality findings and instance binding findings are reported on report instead.

class pyxsd.xslt.ExtensionInstruction

One registered application instruction and its executor.

name is the instruction’s expanded QName ({uri}local); compiler compiles the element into the application’s own plan on this compilation’s static context, and executor executes that plan through the compiled artifact’s per-artifact snapshot. Both are application-supplied callables; the engine never inspects the plan type at registration time, so the executor binding is discovered when the first instruction of the family is compiled.

name: str
compiler: pyxsd.xslt.compiler.dispatch.InstructionCompiler
executor: pyxsd.xslt.runtime.dispatch.PlanExecutor
class pyxsd.xslt.ExtensionSignature

Declared parameter and result sequence types for one extension.

parameters: tuple[str, ...] = ()
result: str = 'item()*'
property parsed_parameters: tuple[_SequenceType, ...]
Return type:

tuple[_SequenceType, …]

property parsed_result: _SequenceType
Return type:

_SequenceType

class pyxsd.xslt.XsltExtensions

An immutable registry of extension functions, instructions, collations.

Instruction registrations (register_instruction()) declare trusted application extension elements the compiler recognizes before literal-result handling; each carries the application’s own compiler and plan executor and is captured on the compiled artifact it was compiled with.

property functions: collections.abc.Mapping[tuple[str, int], ExtensionFunction]

Registered functions keyed by expanded name and arity.

Return type:

collections.abc.Mapping[tuple[str, int], ExtensionFunction]

property collations: collections.abc.Mapping[str, Any]

Registered collations keyed by absolute URI.

Return type:

collections.abc.Mapping[str, Any]

property python_rules: pyxsd.xslt.python_rules.PythonRules

The immutable Python customization rules captured at compile time.

Return type:

pyxsd.xslt.python_rules.PythonRules

property instructions: collections.abc.Mapping[str, ExtensionInstruction]

Registered instructions keyed by expanded QName.

Return type:

collections.abc.Mapping[str, ExtensionInstruction]

with_python_rules(rules)

Return a new registry carrying rules.

Parameters:

rules (pyxsd.xslt.python_rules.PythonRules)

Return type:

XsltExtensions

function(name, arity, signature=NO_ARGS)

Return a registrar for one function, preserving immutability.

Parameters:
Return type:

collections.abc.Callable[…, XsltExtensions]

register_function(name, arity, callback, signature=NO_ARGS, *, contextual=False)

Return a new registry with one Python callback registered.

Parameters:
Return type:

XsltExtensions

collation(uri, *, compare=None, sort_key=None)

Return a new registry with one custom collation registered.

Parameters:
Return type:

XsltExtensions

register_instruction(name, *, compiler, executor)

Return a new registry with one application instruction registered.

name must be an expanded QName in the application’s own namespace; the private urn:pyxsd:python-rules namespace belongs to the generated customization layer and can never be registered. The compiled artifact keeps this registration as an immutable per-compilation and per-artifact snapshot, so a later registration never changes an artifact that was compiled without it.

Parameters:
  • name (str)

  • compiler (pyxsd.xslt.compiler.dispatch.InstructionCompiler)

  • executor (pyxsd.xslt.runtime.dispatch.PlanExecutor)

Return type:

XsltExtensions

function_available(name, arity=None)

Whether the registry declares name (an expanded or lexical QName).

Parameters:
  • name (str)

  • arity (int | None)

Return type:

bool

availability()

The expanded-name/arity pairs of every registered function.

Return type:

frozenset[tuple[str, int]]

resolve(namespaces, *, identity=None)

Resolve every lexical registration against one stylesheet scope.

Parameters:
Return type:

XsltExtensions

runtime_targets(context_item=None, *, existing=None, profile=None)

Runtime targets keyed by expanded function name.

existing supplies the stylesheet-function dispatchers already in the environment. A name registered both as an extension and as a stylesheet function keeps both arities: extension arities route to the Python callback and every other arity routes to the existing dispatcher. profile restricts callback results to the active processor’s data model.

Parameters:
Return type:

collections.abc.Mapping[str, ExtensionTarget]

pyxsd.xslt.no_args: Final
pyxsd.xslt.xs_integer_to_integer: Final
class pyxsd.xslt.InspectionDiagnostic

One classified, advisory inspection finding.

code is the underlying pyxsd/XSD diagnostic code. It is never a normative XSLT error code.

code: str
message: str
classification: DiagnosticClassification
rationale: str
severity: str = 'error'
phase: str = 'schema'
element: str | None = None
format()

Render the diagnostic as one advisory line.

Return type:

str

class pyxsd.xslt.StylesheetInspection

The result of advisory stylesheet inspection.

capability describes the inspection profile, not stylesheet validity. A bound result carries a Document; an unsupported result carries no document and explains itself through report and diagnostics.

capability: StylesheetCapability
language: str
document: pyxsd.document.Document | None
report: pyxsd.validation.ValidationReport
diagnostics: tuple[InspectionDiagnostic, ...]
pyxsd.xslt.inspect_stylesheet(source, *, language='3.0', resource_policy=None)

Bind one stylesheet module as an advisory, non-normative structural view.

source is a path or readable stream. language selects the packaged XSLT 2.0 or 3.0 schema (default "3.0"). A supplied resource_policy governs every read, including the packaged local schemas; a policy that denies them makes inspection fail.

Resource and input failures raise XsltInspectionError. Schema and binding findings never raise and never become normative XTSE* errors; they are reported on the returned inspection together with a classified diagnostic for each finding.

Parameters:
Return type:

StylesheetInspection

class pyxsd.xslt.OutputPolicy

Authorize one absolute output URI before its content is constructed.

authorize(uri, *, principal)

Raise a resource policy error when the destination is not allowed.

Parameters:
Return type:

None

class pyxsd.xslt.CompiledStylesheet

One immutable compiled stylesheet or package.

processor: XsltProcessor
package: pyxsd.xslt.compiler.packages.CompiledPackage
schema_pool: pyxsd.xdm.schema.SchemaPool | None
profile: pyxsd.xslt.compiler.context.ProfileOptions
static_parameters: collections.abc.Mapping[str, Any]
extensions: pyxsd.xslt.extensions.XsltExtensions
plan_executors: collections.abc.Mapping[type[pyxsd.xslt.compiler.plans._Plan], pyxsd.xslt.runtime.dispatch.PlanExecutor]
property language: str
Return type:

str

property xpath: str
Return type:

str

property name: str | None
Return type:

str | None

property version: str
Return type:

str

property mode_names: tuple[str | None, ...]
Return type:

tuple[str | None, …]

mode_rule_count(mode=None)

Number of compiled template rules in mode, including package layers.

Parameters:

mode (str | None)

Return type:

int

function_available(name, arity)
Parameters:
Return type:

bool

transform(source=_ABSENT, *, parameters=None, global_context_item=_ABSENT, initial_match_selection=_ABSENT, template_parameters=None, tunnel_parameters=None, initial_template=None, initial_mode=None, initial_function=None, initial_function_arguments=(), output_uri=None, delivery='stylesheet', principal_serialization=None, limits=None, validation=None, validation_type=None, _budget=None, _check_principal=None)

Run one fresh invocation of this compiled stylesheet.

For stylesheet delivery, principal_serialization overrides the principal output attributes before serialization and byte accounting. Secondary results keep their own output attributes.

Parameters:
Return type:

pyxsd.xslt.results.TransformationResult

as_transform(*, target_schema, on_result=None)

Expose this compiled stylesheet as a pyxsd document transform.

Returns the XsltDocumentTransform adapter wired to this compiled artifact and its extension snapshot. Document.transform dispatches the adapter before the legacy root callables, so document.transform(sheet.as_transform(target_schema=schema)) runs the stylesheet with explicit document delivery over the document’s coherent XDM and returns a fresh document bound directly from the principal result. A compiled XSD or RELAX NG target_schema validates the result; pass None for a schemaless document with lexical typing and a current empty report. Secondary results and messages are ancillary output: the transform is rejected unless on_result receives the complete transformation result; the callback only observes.

This method constructs the adapter only: conversion, validation, and result handling live in pyxsd.xslt.adapter.

Raises:

TypeError – The target is neither a compiled XSD or RELAX NG schema nor None, or on_result is neither a callable nor None.

Parameters:
Return type:

pyxsd.xslt.adapter.XsltDocumentTransform

exception pyxsd.xslt.XsltInvocationError(message, *, code=None)

An invalid host invocation option combination.

code carries the XSLT dynamic error code when the specification gives one (for example XTDE0044 for an initial mode without a match selection). The fn:transform adapter can reuse this validator and map the code without conflating source, global context, and selection inputs.

Parameters:
  • message (str)

  • code (str | None)

code = None
class pyxsd.xslt.XsltProcessor

Immutable processor identity and resource configuration.

The default is an XSLT 3.0 processor with XPath 3.1 and schema awareness. language="2.0" (with the matching xpath="2.0") builds the native, schema-aware XSLT 2.0 processor: a distinct identity with its own static feature gate, XPath surface, recovery table, and serialization method selection, all owned by the profile layer. Extension registries ride on either identity; this processor rejects a profile it cannot execute instead of silently running different semantics.

remote_resource_policy separately authorizes stylesheet-driven remote document reads. Its trusted implementation must constrain origins, redirects, timeouts and resource consumption. It does not authorize output writes.

language: str = '3.0'
xpath: str = '3.1'
schema_aware: bool = True
xsd_version: str = '1.1'
validation: str = 'strip'
validation_type: str | None = None
default_collation: str | None = None
implicit_timezone: Any = None
resource_policy: Any = None
remote_resource_policy: Any = None
collection_resolver: collections.abc.Callable[[str | None], collections.abc.Sequence[pyxsd.xdm.nodes.XdmNode]] | None = None
xml_policy: Any = None
xml_limits: Any = None
resolver: pyxsd.xslt.compiler.packages.PackageResolver | None = None
static_options: collections.abc.Mapping[str, Any]
recovery_policy: pyxsd.xslt.profiles.RecoveryPolicy | None = None
output_policy: pyxsd.xslt.policy.OutputPolicy | None = None
compile(source, *, static_parameters=None, schema=None, extensions=None)

Compile one ordinary, simplified, or package stylesheet.

Compilation completes the module/package closure and every expression, pattern, and value template this vertical slice can execute. A static failure raises XsltStaticError; no partial executable artifact is returned. extensions is an immutable Python extension registry; the compiled artifact keeps that snapshot.

Parameters:
Return type:

CompiledStylesheet

class pyxsd.xslt.PythonRuleContext

The restricted dynamic context passed to every Python rule callback.

parameters is the current bound local frame. Delegation is legal only for the registered role; an unavailable operation raises XTDE0560 and an abstract original without an implementation raises XTDE0040.

context_item: pyxsd.xdm.XdmItem | None = None
parameters: collections.abc.Mapping[str, pyxsd.xdm.XdmSequence]
invoke_original(*arguments)

Execute the XML component this named override replaced.

Parameters:

arguments (Any)

Return type:

pyxsd.xdm.XdmSequence

next_match()

Continue with the next template rule in conflict-resolution order.

Return type:

pyxsd.xdm.XdmSequence

apply_imports()

Continue with the next lower import-precedence template rule.

Return type:

pyxsd.xdm.XdmSequence

class pyxsd.xslt.PythonRules

An immutable set of Python component overrides and mode rules.

classmethod empty()

Return an empty registry.

Return type:

PythonRules

override_template(name, callback)

Return a registry that replaces one named template.

Parameters:
Return type:

PythonRules

override_function(name, arity, callback)

Return a registry that replaces one stylesheet function.

Parameters:
Return type:

PythonRules

add_mode_rule(mode, match, callback, *, priority=None)

Return a registry that adds one template rule to a named mode.

Parameters:
Return type:

PythonRules

property entries: tuple[_PythonRule, ...]
Return type:

tuple[_PythonRule, …]

property bound: tuple[_BoundPythonRule, ...]
Return type:

tuple[_BoundPythonRule, …]

property rule_count: int
Return type:

int

property original_components: collections.abc.Mapping[pyxsd.xslt.compiler.components.ComponentKey, pyxsd.xslt.compiler.components.Component]
Return type:

collections.abc.Mapping[pyxsd.xslt.compiler.components.ComponentKey, pyxsd.xslt.compiler.components.Component]

property original_plans: collections.abc.Mapping[pyxsd.xslt.compiler.components.ComponentKey, pyxsd.xslt.compiler.plans._ComponentPlan]
Return type:

collections.abc.Mapping[pyxsd.xslt.compiler.components.ComponentKey, pyxsd.xslt.compiler.plans._ComponentPlan]

resolve(namespaces, *, identity=None)

Resolve lexical names against one stylesheet’s in-scope namespaces.

Parameters:
Return type:

PythonRules

class pyxsd.xslt.Message

One stylesheet message or diagnostic event.

text is the message’s string value (what a serializer or console emits). content is the document node an xsl:message sequence constructor builds, which XSLT 3.0 section 18.1 makes the message’s value: a listener or a conformance assertion inspects its nodes, not just the text. It is None only when the message constructor failed before producing content.

text: str
code: str | None = None
uri: str | None = None
terminate: bool = False
content: pyxsd.xdm.nodes.XdmDocument | None = None
class pyxsd.xslt.ResultEntry

One principal or secondary result in every available view.

raw is the exact XDM sequence. tree is the delivered document when tree construction was requested and possible. serialized is the serialized string when delivery="stylesheet" produced one, while serialization records the effective output parameters. output_uri identifies the principal result or the absolute URI of a secondary result. character_maps holds the resolved (character, replacement) pairs for the effective output, so an explicit serialize() or write() reproduces the transformation’s own serialization. effective_serialization records the parameters used for the delivered string, including defaults and invocation overrides, when available.

raw: pyxsd.xdm.values.XdmSequence
output_uri: str | None = None
tree: pyxsd.xdm.nodes.XdmDocument | None = None
serialized: str | None = None
serialization: collections.abc.Mapping[str, str]
character_maps: tuple[tuple[str, str], ...] = ()
legacy: bool = False
messages: tuple[Message, ...] = ()
effective_serialization: pyxsd.xslt.serialization.SerializationParameters | None = None
property document: pyxsd.xdm.nodes.XdmDocument | None

The separately delivered document, when sequence normalization built one.

Return type:

pyxsd.xdm.nodes.XdmDocument | None

exception pyxsd.xslt.ResultShapeError

The requested result view does not have the required shape.

A raw sequence of atomics, maps, or arrays is a valid principal result but is not a document tree. Tree delivery must be requested explicitly (or by the stylesheet’s output defaults); the raw sequence is never silently wrapped.

class pyxsd.xslt.TransformationResult

The principal and secondary results of one transformation.

The result retains its invocation’s output policy only so an explicit write() can authorize the same destination again. Producing the result, serialize(), and principal_tree() never write.

principal_entry: ResultEntry
secondary: collections.abc.Mapping[str, ResultEntry]
messages: tuple[Message, ...] = ()
warnings: tuple[str, ...] = ()
property principal: pyxsd.xdm.values.XdmSequence

The raw principal XDM sequence, before delivery normalization.

Return type:

pyxsd.xdm.values.XdmSequence

property principal_tree: pyxsd.xdm.nodes.XdmDocument

The delivered principal document, or an explicitly document-shaped raw result.

Raises ResultShapeError rather than wrapping a non-document sequence or silently serializing and reparsing it.

Return type:

pyxsd.xdm.nodes.XdmDocument

to_document(schema, *, uri=None)

Bind one result as a schema-bound or schemaless XML document.

Omit uri for the principal result, or pass the exact absolute URI of a secondary result. The selected entry must have a delivered document tree or a single raw XDM document. Binding uses that tree directly and leaves all results and messages available. A RELAX NG target’s captured XDM has no XSD occurrence annotations. Do not bind concurrently or reentrantly to the same schema. Pass None for a fresh schemaless document with a current empty report and lexical typing. Its untyped XDM view reflects the editable tree, which omits comments and processing instructions.

Raises:
  • KeyError – The secondary URI is unknown.

  • ResultShapeError – The selected entry is not a document tree, or the tree has no document element.

  • ValidationError – The document fails validation. The exception carries the target validation report.

  • TypeError – The schema is neither a compiled XSD or RELAX NG schema nor None.

Parameters:
Return type:

pyxsd.document.Document

to_json_document(*, uri=None)

Convert one raw result to an independent native JSON document.

Omit uri for the principal result, whose source is "<memory>", or select a secondary result by its exact absolute URI, which becomes the document’s source. The document has a native type policy and an empty validation report. Conversion does not serialize or perform I/O and leaves all results and messages available.

Empty sequences are null and singleton sequences convert directly, including map values and array members. Maps require xs:string keys, and only XDM arrays become arrays. Strings, untyped atomics, and booleans become native scalars. Integers (including derived integers) and decimals keep their exact value as int and Decimal; finite doubles and floats become float.

Raises:
  • KeyError – The secondary URI is unknown.

  • ResultShapeError – The raw result contains a multi-item sequence, a non-string map key, an XML node, a function, an unsupported atomic type, or a non-finite number.

Parameters:

uri (str | None)

Return type:

pyxsd.schemaless.json_document.JsonDocument

serialize(uri=None, *, parameters=None)

Return one result as a string, without authorization or I/O.

uri selects the principal result when None and exactly that secondary key otherwise. parameters override the entry’s retained effective output attributes for this call only.

Parameters:
Return type:

str

write(destination, uri=None, *, parameters=None)

Write one result after re-authorizing its absolute output URI.

uri selects the principal result when None and exactly that secondary key otherwise. Writing is always an explicit host operation: the entry must already carry an absolute output URI, and a configured output policy authorizes this destination again with principal=(uri is None). A destination OSError becomes a code=None dynamic error retaining the original exception, except for an execution-budget alarm, which is re-raised: TimeoutError is one class, so a destination’s own timeout and the caller’s alarm are indistinguishable here, and the alarm is the likelier origin once a budget is set.

Encoded bytes share the invocation’s max_output_bytes budget with stylesheet delivery, nested transforms, and previous writes. Each write encodes again. To deliver again after exhausting the budget, run the transformation with a larger limit or with None. On failure a binary destination can retain the prefix written so far; a path opened by this call is closed without removal.

Parameters:
Return type:

None

class pyxsd.xslt.ExecutionLimits

Explicit budgets for one transformation and its nested invocations.

max_frames defaults to 100,000 live explicit frames. Non-tail arithmetic recursion keeps frames for its pending work, as do supported terminal stylesheet calls in text value templates and template dispatch in literal result content. The scheduled content includes nested literals, xsl:sequence bodies, xsl:if and xsl:choose, xsl:try and xsl:catch, xsl:for-each, xsl:for-each-group and xsl:iterate bodies, xsl:fork branches, and selected xsl:fallback bodies.

Python can stop recursion first in literal construction under a live merge scope and in text value templates inside scheduled literal content. Other synchronous content includes xsl:value-of, xsl:attribute, xsl:comment, xsl:processing-instruction, xsl:namespace, xsl:element, xsl:document, xsl:copy, xsl:map, xsl:map-entry, xsl:variable, xsl:param, xsl:with-param (including in xsl:evaluate), xsl:break, xsl:next-iteration parameters, xsl:on-completion, xsl:perform-sort, xsl:sort and xsl:merge-key constructors, xsl:merge-action, xsl:source-document, xsl:result-document, xsl:analyze-string substring bodies, xsl:assert, xsl:message, xsl:where-populated, xsl:on-empty and xsl:on-non-empty. The same limit can stop fallback XPath, such as ($n, f($n - 1)), a stylesheet function building nested elements (including adaptation of a deep result tree on XPath resume), or a long static XPath path. The depth depends on the interpreter and its version.

Frame-budget exhaustion and RecursionError caught at scheduler guards raise an uncatchable XsltDynamicError with code PYXSD-XSLT-001. In CPython 3.13.8 through 3.13.12, a specialized bound method call at the recursion ceiling can raise an unrelated TypeError instead of RecursionError (CPython issue gh-145008).

A safe tail call replaces its frame in place. Use max_steps to bound the number of scheduler dispatches in a tail-call chain; max_frames does not bound the length of that chain. max_steps does not interrupt work within one dispatch. max_documents bounds loaded XML documents. These and other limits described here default to None unless stated otherwise.

With the default max_steps=None, the processor does not stop an unbounded safe tail recursion; callers bound such a chain by setting max_steps.

max_resource_bytes bounds octets the transformation runtime acquires. Top-level stylesheet compilation reads and schema loads made by xsl:import-schema are outside this budget. A host ResourcePolicy.read() can allocate a whole resource before handing it over; the budget charges its returned bytes at that handoff.

max_annotations defaults to 262,144 atomic type annotation entries recorded cumulatively across the transformation and its nested calls. It governs runtime tables; static XPath evaluation during stylesheet compilation precedes invocation and uses the XPath engine’s own default. Each runtime table retains the values for its invocation’s lifetime, so disabling the cap allows memory to grow with the number of distinct typed values bridged to or from XPath.

max_output_nodes counts raw principal and secondary output nodes, their descendants and owned attributes, once by identity per result entry. Namespace nodes and implicit normalization document nodes are excluded; text nodes that normalization merges are counted separately. This bounds delivered nodes, not memory: provisional constructor and copy trees are built before their final nodes can be admitted. max_output_bytes bounds bytes encoded for stylesheet delivery and later write() calls. Writing a result again spends the same budget. To deliver again after exhausting that budget, run the transformation with a larger limit or with None.

None disables any limit. Nested transforms inherit the settings unchanged and share the cumulative ledger; frames count while live. Exhaustion raises an uncatchable XsltDynamicError with code PYXSD-XSLT-001.

max_frames: int | None = 100000
max_steps: int | None = None
max_documents: int | None = None
max_output_nodes: int | None = None
max_output_bytes: int | None = None
max_resource_bytes: int | None = None
max_annotations: int | None = 262144