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¶
A dynamic error raised while executing a transformation. |
|
Advisory stylesheet inspection could not read or bind its inputs. |
|
An invalid host invocation option combination. |
|
The requested result view does not have the required shape. |
Classes¶
One registered application instruction and its executor. |
|
Declared parameter and result sequence types for one extension. |
|
An immutable registry of extension functions, instructions, collations. |
|
One classified, advisory inspection finding. |
|
The result of advisory stylesheet inspection. |
|
Authorize one absolute output URI before its content is constructed. |
|
One immutable compiled stylesheet or package. |
|
Immutable processor identity and resource configuration. |
|
The restricted dynamic context passed to every Python rule callback. |
|
An immutable set of Python component overrides and mode rules. |
|
One stylesheet message or diagnostic event. |
|
One principal or secondary result in every available view. |
|
The principal and secondary results of one transformation. |
|
Explicit budgets for one transformation and its nested invocations. |
Functions¶
|
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.
codeis normally an XSLTXTDE/XTTEcode or an XPath error code. The execution runtime’s own resource limits use the stable implementation codePYXSD-XSLT-001; callers can test it exactly without depending on message text.allow_catchis false for foreign callback failures that crossed an XSLT boundary without being deliberately converted.- Parameters:
message (str)
code (str | None)
phase (str)
uri (str | None)
module (str | None)
package (str | None)
location (pyxsd.locations.IssueLocation | None)
stack (collections.abc.Sequence[pyxsd.xslt.runtime.frames.FrameDiagnostic])
cause (BaseException | None)
allow_catch (bool)
description (str | None)
has_description (bool)
value (collections.abc.Sequence[object])
line_number (int | None)
column_number (int | None)
- allow_catch = True¶
- 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
reportinstead.
- 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.- 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.
- 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:
- property instructions: collections.abc.Mapping[str, ExtensionInstruction]¶
Registered instructions keyed by expanded QName.
- Return type:
- with_python_rules(rules)¶
Return a new registry carrying rules.
- Parameters:
- Return type:
- function(name, arity, signature=NO_ARGS)¶
Return a registrar for one function, preserving immutability.
- Parameters:
name (str)
arity (int)
signature (ExtensionSignature)
- Return type:
- register_function(name, arity, callback, signature=NO_ARGS, *, contextual=False)¶
Return a new registry with one Python callback registered.
- Parameters:
name (str)
arity (int)
callback (collections.abc.Callable[..., Any])
signature (ExtensionSignature)
contextual (bool)
- Return type:
- collation(uri, *, compare=None, sort_key=None)¶
Return a new registry with one custom collation registered.
- Parameters:
uri (str)
compare (collections.abc.Callable[[str, str], int] | None)
sort_key (collections.abc.Callable[[str], Any] | None)
- Return type:
- 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-rulesnamespace 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:
- function_available(name, arity=None)¶
Whether the registry declares name (an expanded or lexical QName).
- availability()¶
The expanded-name/arity pairs of every registered function.
- resolve(namespaces, *, identity=None)¶
Resolve every lexical registration against one stylesheet scope.
- Parameters:
namespaces (collections.abc.Mapping[str, str])
identity (str | None)
- Return type:
- 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:
context_item (pyxsd.xdm.XdmItem | None)
existing (collections.abc.Mapping[str, Any] | None)
profile (pyxsd.xslt.profiles.LanguageProfile | None)
- 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.
codeis the underlying pyxsd/XSD diagnostic code. It is never a normative XSLT error code.- classification: DiagnosticClassification¶
- class pyxsd.xslt.StylesheetInspection¶
The result of advisory stylesheet inspection.
capabilitydescribes the inspection profile, not stylesheet validity. Aboundresult carries aDocument; anunsupportedresult carries no document and explains itself throughreportanddiagnostics.- capability: StylesheetCapability¶
- document: pyxsd.document.Document | None¶
- 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.
sourceis a path or readable stream.languageselects the packaged XSLT 2.0 or 3.0 schema (default"3.0"). A suppliedresource_policygoverns 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 normativeXTSE*errors; they are reported on the returned inspection together with a classified diagnostic for each finding.- Parameters:
source (str | os.PathLike[str] | IO[str])
language (str)
resource_policy (pyxsd.resource_policy.ResourcePolicy | None)
- Return type:
- class pyxsd.xslt.OutputPolicy¶
Authorize one absolute output URI before its content is constructed.
- class pyxsd.xslt.CompiledStylesheet¶
One immutable compiled stylesheet or package.
- processor: XsltProcessor¶
- package: pyxsd.xslt.compiler.packages.CompiledPackage¶
- 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]¶
- mode_rule_count(mode=None)¶
Number of compiled template rules in mode, including package layers.
- 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:
source (Any)
parameters (collections.abc.Mapping[str, Any] | None)
global_context_item (Any)
initial_match_selection (Any)
template_parameters (collections.abc.Mapping[str, Any] | None)
tunnel_parameters (collections.abc.Mapping[str, Any] | None)
initial_template (str | None)
initial_mode (str | None)
initial_function (str | None)
initial_function_arguments (collections.abc.Sequence[Any])
output_uri (str | None)
delivery (str)
principal_serialization (collections.abc.Mapping[str, Any] | None)
limits (Any)
validation (str | None)
validation_type (str | None)
_budget (pyxsd.xslt.runtime.frames.ExecutionBudget | None)
_check_principal (collections.abc.Callable[[pyxsd.xdm.XdmSequence], None] | None)
- Return type:
- as_transform(*, target_schema, on_result=None)¶
Expose this compiled stylesheet as a pyxsd document transform.
Returns the
XsltDocumentTransformadapter wired to this compiled artifact and its extension snapshot.Document.transformdispatches the adapter before the legacy root callables, sodocument.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; passNonefor 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 norNone.- Parameters:
target_schema (pyxsd.schema.Schema | pyxsd.relaxng.RelaxNGSchema | None)
on_result (collections.abc.Callable[[pyxsd.xslt.results.TransformationResult], None] | None)
- Return type:
pyxsd.xslt.adapter.XsltDocumentTransform
- exception pyxsd.xslt.XsltInvocationError(message, *, code=None)¶
An invalid host invocation option combination.
codecarries the XSLT dynamic error code when the specification gives one (for exampleXTDE0044for 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.- 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 matchingxpath="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_policyseparately authorizes stylesheet-driven remote document reads. Its trusted implementation must constrain origins, redirects, timeouts and resource consumption. It does not authorize output writes.- 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¶
- static_options: collections.abc.Mapping[str, Any]¶
- 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:
source (Any)
static_parameters (collections.abc.Mapping[str, Any] | None)
schema (Any)
extensions (pyxsd.xslt.extensions.XsltExtensions | None)
- Return type:
- class pyxsd.xslt.PythonRuleContext¶
The restricted dynamic context passed to every Python rule callback.
parametersis the current bound local frame. Delegation is legal only for the registered role; an unavailable operation raisesXTDE0560and an abstract original without an implementation raisesXTDE0040.- 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:
- next_match()¶
Continue with the next template rule in conflict-resolution order.
- Return type:
- apply_imports()¶
Continue with the next lower import-precedence template rule.
- Return type:
- class pyxsd.xslt.PythonRules¶
An immutable set of Python component overrides and mode rules.
- classmethod empty()¶
Return an empty registry.
- Return type:
- override_template(name, callback)¶
Return a registry that replaces one named template.
- Parameters:
name (str)
callback (collections.abc.Callable[[PythonRuleContext], Any])
- Return type:
- override_function(name, arity, callback)¶
Return a registry that replaces one stylesheet function.
- Parameters:
name (str)
arity (int)
callback (collections.abc.Callable[[PythonRuleContext], Any])
- Return type:
- add_mode_rule(mode, match, callback, *, priority=None)¶
Return a registry that adds one template rule to a named mode.
- Parameters:
mode (str | None)
match (str)
callback (collections.abc.Callable[[PythonRuleContext], Any])
priority (decimal.Decimal | int | str | None)
- Return type:
- 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:
namespaces (collections.abc.Mapping[str, str])
identity (str | None)
- Return type:
- class pyxsd.xslt.Message¶
One stylesheet message or diagnostic event.
textis the message’s string value (what a serializer or console emits).contentis the document node anxsl:messagesequence 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 isNoneonly when the message constructor failed before producing content.- content: pyxsd.xdm.nodes.XdmDocument | None = None¶
- class pyxsd.xslt.ResultEntry¶
One principal or secondary result in every available view.
rawis the exact XDM sequence.treeis the delivered document when tree construction was requested and possible.serializedis the serialized string whendelivery="stylesheet"produced one, whileserializationrecords the effective output parameters.output_uriidentifies the principal result or the absolute URI of a secondary result.character_mapsholds the resolved(character, replacement)pairs for the effective output, so an explicitserialize()orwrite()reproduces the transformation’s own serialization.effective_serializationrecords the parameters used for the delivered string, including defaults and invocation overrides, when available.- tree: pyxsd.xdm.nodes.XdmDocument | None = None¶
- serialization: collections.abc.Mapping[str, str]¶
- 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(), andprincipal_tree()never write.- principal_entry: ResultEntry¶
- secondary: collections.abc.Mapping[str, ResultEntry]¶
- property principal: pyxsd.xdm.values.XdmSequence¶
The raw principal XDM sequence, before delivery normalization.
- Return type:
- property principal_tree: pyxsd.xdm.nodes.XdmDocument¶
The delivered principal document, or an explicitly document-shaped raw result.
Raises
ResultShapeErrorrather than wrapping a non-document sequence or silently serializing and reparsing it.- Return type:
- 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
Nonefor 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:
schema (pyxsd.schema.Schema | pyxsd.relaxng.RelaxNGSchema | None)
uri (str | None)
- Return type:
- 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:stringkeys, and only XDM arrays become arrays. Strings, untyped atomics, and booleans become native scalars. Integers (including derived integers) and decimals keep their exact value asintandDecimal; finite doubles and floats becomefloat.- 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:
- serialize(uri=None, *, parameters=None)¶
Return one result as a string, without authorization or I/O.
uri selects the principal result when
Noneand exactly that secondary key otherwise. parameters override the entry’s retained effective output attributes for this call only.- Parameters:
uri (str | None)
parameters (collections.abc.Mapping[str, Any] | None)
- Return type:
- write(destination, uri=None, *, parameters=None)¶
Write one result after re-authorizing its absolute output URI.
uri selects the principal result when
Noneand 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 withprincipal=(uri is None). A destinationOSErrorbecomes acode=Nonedynamic error retaining the original exception, except for an execution-budget alarm, which is re-raised:TimeoutErroris 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_bytesbudget 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 withNone. On failure a binary destination can retain the prefix written so far; a path opened by this call is closed without removal.- Parameters:
destination (Any)
uri (str | None)
parameters (collections.abc.Mapping[str, Any] | None)
- Return type:
None
- class pyxsd.xslt.ExecutionLimits¶
Explicit budgets for one transformation and its nested invocations.
max_framesdefaults 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:sequencebodies,xsl:ifandxsl:choose,xsl:tryandxsl:catch,xsl:for-each,xsl:for-each-groupandxsl:iteratebodies,xsl:forkbranches, and selectedxsl:fallbackbodies.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 inxsl:evaluate),xsl:break,xsl:next-iterationparameters,xsl:on-completion,xsl:perform-sort,xsl:sortandxsl:merge-keyconstructors,xsl:merge-action,xsl:source-document,xsl:result-document,xsl:analyze-stringsubstring bodies,xsl:assert,xsl:message,xsl:where-populated,xsl:on-emptyandxsl: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
RecursionErrorcaught at scheduler guards raise an uncatchableXsltDynamicErrorwith codePYXSD-XSLT-001. In CPython 3.13.8 through 3.13.12, a specialized bound method call at the recursion ceiling can raise an unrelatedTypeErrorinstead ofRecursionError(CPython issue gh-145008).A safe tail call replaces its frame in place. Use
max_stepsto bound the number of scheduler dispatches in a tail-call chain;max_framesdoes not bound the length of that chain.max_stepsdoes not interrupt work within one dispatch.max_documentsbounds loaded XML documents. These and other limits described here default toNoneunless stated otherwise.With the default
max_steps=None, the processor does not stop an unbounded safe tail recursion; callers bound such a chain by settingmax_steps.max_resource_bytesbounds octets the transformation runtime acquires. Top-level stylesheet compilation reads and schema loads made byxsl:import-schemaare outside this budget. A hostResourcePolicy.read()can allocate a whole resource before handing it over; the budget charges its returned bytes at that handoff.max_annotationsdefaults 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_nodescounts 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_bytesbounds bytes encoded for stylesheet delivery and laterwrite()calls. Writing a result again spends the same budget. To deliver again after exhausting that budget, run the transformation with a larger limit or withNone.Nonedisables any limit. Nested transforms inherit the settings unchanged and share the cumulative ledger; frames count while live. Exhaustion raises an uncatchableXsltDynamicErrorwith codePYXSD-XSLT-001.