pyxsd.relaxng

Native RELAX NG 1.0 support.

The package exposes its public contracts as each stage lands. It does not re-export RELAX NG names from pyxsd, and it never routes RELAX NG work through the XSD compiler.

Submodules

Attributes

Exceptions

AmbiguousValueError

No single scalar interpretation is authoritative for a position.

RelaxNGCompactSyntaxError

A compact-syntax source could not be read into a schema.

RelaxNGLimitError

A configured RELAX NG budget was exhausted.

StaleInterpretationError

A retained interpretation belongs to an older schema revision.

Classes

NodeAnnotations

Immutable annotation view for one lexical element occurrence.

ScalarAnnotation

One typed scalar position on a lexical element.

RelaxNGDocument

One RELAX NG parse revision with its fresh merged report.

CandidateSelection

Require one contract candidate at one exact parse occurrence.

RelaxNGComponentDescription

One immutable component of a compiled RELAX NG grammar.

RelaxNGSchemaDescription

A deterministic grammar inventory.

RelaxNGLimits

Optional budgets for pattern-graph, evidence, capture, and diagnostics.

RelaxNGSchema

An immutable compiled RELAX NG 1.0 schema.

RelaxNGElement

The lexical node used by RELAX NG documents and their projections.

AlternativeValue

One immutable, non-preferential scalar interpretation snapshot.

ListInterpretation

One whole-list contract with correlated token assignment evidence.

Functions

describe_component(schema, component_id)

Return one exact component, raising KeyError for any other ID.

describe_schema(schema)

Return the immutable grammar inventory, valid schema or not.

find_components(schema, *[, text, kind, namespace])

Filter by literal case-insensitive text, component kind, and namespace.

related_components(schema, component_id, *, direction, ...)

Breadth-first component traversal, excluding the seed and duplicates.

Package Contents

class pyxsd.relaxng.NodeAnnotations

Immutable annotation view for one lexical element occurrence.

patterns is the sorted union of surviving authored origins at every scalar and structural site of this element. definitions names the compiled grammar definitions whose origins intersect those surviving origins. scalar retains the deterministic typed scalar sites. There is deliberately no singular matched pattern or type.

schema_id: str
revision_id: int
patterns: tuple[pyxsd.relaxng.origins.SourceOrigin, ...]
definitions: tuple[str, ...]
scalar: tuple[ScalarAnnotation, ...]
complete: bool
class pyxsd.relaxng.ScalarAnnotation

One typed scalar position on a lexical element.

kind="text" identifies character data at a content_index in the element’s ordered content, including child tails; kind="attribute" identifies one present attribute by its expanded name. value retains every surviving candidate; the annotation never selects a preferred branch.

kind: Literal['text', 'attribute']
name: str | None
content_index: int | None
value: pyxsd.relaxng.values.AlternativeValue
class pyxsd.relaxng.RelaxNGDocument(schema, root, source, report, *, typed, capture='none', limits=None, namespace_context=None, declarations=None, xdm_capture=None, interpretations_current=True, attribute_snapshot=None, binding_evidence=None, annotations=None)

One RELAX NG parse revision with its fresh merged report.

typed records whether this parse requested typed access. interpretations_current reports whether the recorded validation and evidence snapshot still belongs to the current, unedited lexical revision. binding_evidence is the immutable evidence graph for a valid typed document, or None for validation-only and invalid typed documents. annotations is the immutable pattern-annotation table for a valid typed parse requested with capture="patterns", materialized lazily on first access, and raises an explicit capability error when capture did not run. root, report, and source keep the lexical tree, the merged schema/instance report, and the original caller source respectively.

Parameters:
schema: pyxsd.relaxng.schema.RelaxNGSchema
root: pyxsd.relaxng.tree.RelaxNGElement
typed: bool
property binding_evidence: pyxsd.relaxng.evidence.EvidenceGraph | None

Internal read-only evidence snapshot for later Phase 3 tasks.

This is not a stable public API. It is the immutable graph for a valid typed document and None for validation-only and invalid typed documents.

Return type:

pyxsd.relaxng.evidence.EvidenceGraph | None

property interpretations_current: bool

Whether the validation snapshot still describes the current revision.

A dirty revision is not current. A current typed snapshot can also be conservatively marked stale by a transform sharing its revision; both documents then report stale until revalidation.

Return type:

bool

property annotations: pyxsd.relaxng.annotations.AnnotationTable

Return this parse revision’s immutable pattern annotations.

Validation-only documents raise an explicit capability error instead of pretending capture ran. A valid typed parse that did not request capture="patterns" raises the same capability family. An invalid typed document raises ValidationError with its report, and an edited or transformed revision raises StaleInterpretationError before either validity or capture is considered.

Materialization is deferred until this property is read. A valid capture-on parse therefore succeeds whenever a capture-off parse does; a declared datatype decoder failure surfaces here, when annotations are explicitly requested, and is retried on the next access because no table is cached after a failed build. Successful tables are cached for this parse revision.

Return type:

pyxsd.relaxng.annotations.AnnotationTable

to_dict(*, typed=True, always_list=False)

Returns the current tree as native pyxsd raw Python values.

The RELAX NG adapter owns the grouped representation; typed=True keeps Python wrappers and raw scalar values, while typed=False reads lexical text. Typed export requires a valid document whose evidence still describes this lexical revision. typed=False remains a lexical escape path for dirty and invalid trees. The adapter receives mode="raw"; none of its values are JSON-encoded.

Parameters:
Return type:

dict

to_data(*, format='pyxsd', fidelity='best-effort', typed=True, always_list=False)

Returns the current tree under a RELAX NG data-format contract.

format="pyxsd" keeps the native grouped representation and converts its scalars to JSON-safe values. The other four formats use their RELAX NG-owned adapters. typed and always_list are native-only options, rejected exactly as the XSD document rejects them on another format. Typed schema-directed output requires a valid, current typed document; native typed=False and JsonML remain lexical escapes over the current tree. The adapter receives mode="json-safe" for JSON-safe scalar output and later tagging.

Parameters:
  • format (pyxsd.data_conversion.contracts.FormatName)

  • fidelity (pyxsd.data_conversion.contracts.Fidelity)

  • typed (bool)

  • always_list (bool)

Return type:

pyxsd.data_conversion.contracts.JsonValue

to_json(*, indent=None, format='pyxsd', fidelity='best-effort', typed=True, always_list=False)

Returns to_data() as standards-compliant JSON text.

No fallback serializer is used: non-finite adapter output is rejected by allow_nan=False instead of emitting a non-JSON token.

Parameters:
  • indent (int | None)

  • format (pyxsd.data_conversion.contracts.FormatName)

  • fidelity (pyxsd.data_conversion.contracts.Fidelity)

  • typed (bool)

  • always_list (bool)

Return type:

str

to_string()

Serialize the current lexical tree, even when typed views are stale.

The writer never consults typed evidence or the parse report, so a dirty or transformed typed document, a validation-only document, and an invalid document all retain this lexical escape path. The root tail is outside the document element and is not written.

Return type:

str

write(dest)

Write the exact lexical serialization to a path or caller file object.

Paths are opened and closed here with UTF-8 encoding. Caller file objects are written and flushed but left open, matching the existing path-versus-file ownership convention. Like to_string(), this reads the current lexical tree without requiring fresh typed evidence.

Parameters:

dest (str | pathlib.Path | os.PathLike[str] | IO[str])

Return type:

None

revalidate()

Validate an independent clone of the current tree.

The lexical tree is cloned into a fresh revision, serialized with the schema-neutral writer, and parsed against the same schema with this document’s typed, capture, XDM, and instance-limit settings. The result has fresh nodes, a fresh report, fresh evidence or a fresh invalid-document interpretation, fresh annotations when captured, and a new revision ID. Projection classes come from the schema’s plan and therefore keep their plan-fixed identity while the nodes are new; candidate IDs stay schema-stable while candidate values are rebuilt. This document, its nodes, report, evidence, and annotations are never refreshed or replaced.

Validation-only documents stay validation-only: the result computes no evidence and exposes no annotation view. Typed documents keep capture mode and its independent annotation budget. The parse’s XDM request is replayed, including for a transformed root that started without a coherent capture, so the returned document owns a fresh coherent XDM view when capture was requested.

Serialization emits the recorded namespace declarations so prefixed QName values keep their external namespace context. The recorded namespace and effective base-URI frames are then restored onto the repared nodes, because a bare string round trip cannot carry a source-relative base URI. A root tail is outside the document element and is not carried into the new document. The lexical writer and to_string/write remain available on the old document and on the result; to_dict, to_data, and to_json dispatch through the RELAX NG adapter registry and apply its freshness policy.

The original DTD declaration evidence is reused without retrieving a DTD or serializing a DOCTYPE. Absent evidence stays absent. Source addresses and XDM capture use the original caller’s source identifier, including a named stream’s name; anonymous inputs stay anonymous. With a trusted resource policy, an original path read may have supplied a different canonical identifier. Revalidation passes a named stream through the policy parser, not its path reader, so that reader’s canonical identifier is not restored.

Return type:

RelaxNGDocument

locate(location)

Resolve one parse-specific occurrence to its lexical node.

RELAX NG parsing records an exact source address for every lexical node instead of building an XSD binding provenance table. This lookup compares those recorded addresses; it never matches by attribute value, local name, or position in another revision. An attribute address returns the parse-time lexical attribute value from this document’s immutable snapshot, so later edits neither change nor create old addresses. An address from another parse is missing.

Parameters:

location (pyxsd.locations.IssueLocation)

Return type:

pyxsd.locations.NodeLookup

exception pyxsd.relaxng.AmbiguousValueError

No single scalar interpretation is authoritative for a position.

Raised by later value interfaces when several schema-defined contracts survive. Callers inspect the alternatives instead of guessing a type.

exception pyxsd.relaxng.RelaxNGCompactSyntaxError(message, *, location=None, found=None, expected=())

A compact-syntax source could not be read into a schema.

Lexical, escape, tokenization, and unrecoverable grammar failures raise this exception. location is the exact source occurrence when known, found describes the offending token, and expected lists the tokens that would have been accepted. The string form starts with source:line:column when span evidence is available.

Parameters:
property location: pyxsd.locations.IssueLocation | None

The source occurrence where the failure was detected.

Return type:

pyxsd.locations.IssueLocation | None

property found: str | None

A description of the token that was found, when known.

Return type:

str | None

property expected: tuple[str, ...]

Descriptions of acceptable tokens, sorted deterministically.

Return type:

tuple[str, …]

exception pyxsd.relaxng.RelaxNGLimitError(stage, budget, configured, observed, *, detail=None)

A configured RELAX NG budget was exhausted.

Budget exhaustion is not semantic invalidity: a schema or instance that exceeds a caller’s budget has no verdict. The attributes name the work that stopped and the observation that crossed the configured value. The compact reader’s fixed interpreter-safety nesting ceiling is reported as an exhausted max_compact_depth budget even when that budget is unset or larger, and detail explains that effective bound.

Parameters:
  • stage (str)

  • budget (str)

  • configured (int)

  • observed (int)

  • detail (str | None)

property stage: str

The compiler or validator stage that exhausted the budget.

Return type:

str

property budget: str

The RelaxNGLimits field name.

Return type:

str

property configured: int

The caller’s configured value for this budget.

Return type:

int

property observed: int

The observed count that exceeded the configured value.

Return type:

int

exception pyxsd.relaxng.StaleInterpretationError

A retained interpretation belongs to an older schema revision.

Raised by later value interfaces when freshness is required and a document or annotation was compiled against a schema that has changed.

class pyxsd.relaxng.CandidateSelection

Require one contract candidate at one exact parse occurrence.

Candidate identity is grammar-scoped; occurrence identity remains parse-local. Equal candidate IDs at distinct sites never collapse these requirements.

occurrence: EvidenceOccurrence
candidate_id: str
class pyxsd.relaxng.RelaxNGComponentDescription

One immutable component of a compiled RELAX NG grammar.

kind is grammar, define, pattern, name-class, datatype, route, or resource. namespace is an expanded-name namespace only (never a datatype-library URI). name is a local name for exact element/attribute patterns and exact name classes, an expanded element name for routes, a datatype type name for datatypes, and the first canonical resource ID for resources; otherwise it is absent. A definition’s name is the composer-generated key. synthetic is true only for these generated definitions, not for patterns or routes; authored define names survive only as origins. owner_id is None for the grammar and "grammar" for all other components: it denotes inventory ownership, not an authored parent. name_class is the canonical presentation of an element/attribute/route/name-class name class. Datatype components carry their normalized library, type, and ordered parameters. There are deliberately no XSD-only fields: no global_declaration, Python binding, occurrence count, or default. Origins union every contributing site. Location is the smallest origin by source ID then source/path/attribute, except resources: their location is the first sorted reference’s location (possibly absent), ordered by containing ID, reference, base, xml:base, canonical ID, then location.

id: str
kind: str
name: str | None
namespace: str | None
location: pyxsd.locations.IssueLocation | None
origins: pyxsd.relaxng.origins.OriginTable
owner_id: str | None
pattern_kind: str | None
name_class: str | None
datatype_library: str | None
datatype_name: str | None
datatype_parameters: tuple[tuple[str, str], ...]
synthetic: bool
class pyxsd.relaxng.RelaxNGSchemaDescription

A deterministic grammar inventory.

start_ids names the compiled start pattern component. Components are sorted by kind rank and then ID; dependencies is the compilation’s canonical resource closure verbatim, including every dependency record whose content merges into one resource component.

start_ids: tuple[str, ...]
components: tuple[RelaxNGComponentDescription, ...]
dependencies: tuple[pyxsd.relaxng.resources.ResourceDependency, ...]
pyxsd.relaxng.describe_component(schema, component_id)

Return one exact component, raising KeyError for any other ID.

Parameters:
Return type:

RelaxNGComponentDescription

pyxsd.relaxng.describe_schema(schema)

Return the immutable grammar inventory, valid schema or not.

An invalid compilation still exposes its grammar, start pattern, definitions, patterns, and resource dependencies. Projection routes are omitted without asking an invalid schema for schema.projection; the report and its verdict are never changed.

Parameters:

schema (pyxsd.relaxng.schema.RelaxNGSchema)

Return type:

RelaxNGSchemaDescription

pyxsd.relaxng.find_components(schema, *, text=None, kind=None, namespace=None)

Filter by literal case-insensitive text, component kind, and namespace.

None leaves a filter unrestricted; an empty namespace selects components without an expanded-name namespace. Text is matched literally over the ID, name, namespace, pattern kind, canonical name class, and datatype library/type; no caller expression is evaluated.

Parameters:
Return type:

tuple[RelaxNGComponentDescription, …]

pyxsd.relaxng.related_components(schema, component_id, *, direction, depth)

Breadth-first component traversal, excluding the seed and duplicates.

Parameters:
Return type:

tuple[RelaxNGComponentDescription, …]

class pyxsd.relaxng.RelaxNGLimits

Optional budgets for pattern-graph, evidence, capture, and diagnostics.

A pattern-node budget counts distinct semantic graph nodes. Derivative, memo-entry, evidence-state, evidence-edge, scalar-witness, and projection-route budgets bound their named work. An evidence binding summary is one retained (occurrence, scalar pattern) record in the schema-static table used for wrapper selection; it is not a proof node, edge, surviving witness, or capture record. max_capture_entries bounds the independent optional annotation table and truncates it visibly instead of raising. A max_diagnostics budget is a truncatable retention budget, not a work budget. max_compact_tokens charges emitted compact tokens cumulatively; max_compact_depth checks the parser’s current nesting depth as a high-water observation rather than charging every production entry, and the compact reader caps that depth at a fixed interpreter-safety ceiling so a larger or unset budget cannot leak RecursionError. The compiler’s graph and semantic correctness checks run regardless of these values; a projection budget never skips a correctness check.

max_pattern_nodes: int | None = None
max_derivative_states: int | None = None
max_memo_entries: int | None = None
max_evidence_states: int | None = None
max_evidence_edges: int | None = None
max_scalar_witnesses: int | None = None
max_binding_summaries: int | None = None
max_capture_entries: int | None = None
max_projection_routes: int | None = None
max_diagnostics: int | None = None
max_compact_tokens: int | None = None
max_compact_depth: int | None = None
class pyxsd.relaxng.RelaxNGSchema

An immutable compiled RELAX NG 1.0 schema.

report holds the merged reader, simplification, composition, and correctness findings of this compilation. grammar is the composed semantic graph with every reference bound; its start may be a Ref edge whose target is the root element pattern. dependencies is the complete canonical resource closure, and namespace_context is the root resource’s namespace context, keeping the authored root frame exactly (an undeclared default namespace remains an empty entry). limits is the schema’s effective budget declaration (unlimited when none was supplied), and datatype_fingerprint identifies the effective datatype registry.

Separate schema objects are independent and may be compiled or used concurrently. One schema does not support reentrant instance parsing; parses of one schema must not run concurrently or reentrantly.

report: pyxsd.validation.ValidationReport
grammar: pyxsd.relaxng.simplify.CompiledGrammar
namespace_context: pyxsd.namespaces.NamespaceContext
limits: pyxsd.relaxng.limits.RelaxNGLimits
datatype_fingerprint: str
classmethod compile(source, *, syntax='auto', datatype_libraries=None, resource_policy=None, xml_policy=None, xml_limits=None, limits=None)

Compile one RELAX NG 1.0 schema in XML or compact syntax.

  • source is a local path or a readable text/binary stream. Remote resources require an authorizing ResourcePolicy; an already-parsed Element is deliberately not accepted because it cannot carry policy parser evidence.

  • syntax selects the root frontend. "auto" (the default) selects compact only for a named root whose path component ends in .rnc, case-insensitively; URL query and fragment components do not participate. Anonymous streams and every other named source stay XML. "xml" and "compact" are explicit overrides. Every include and external dependency inherits the root syntax regardless of its own suffix, so one closure never mixes the two frontends.

  • datatype_libraries maps library URIs to application registrations. It augments the built-in and XSD libraries and may replace a nonreserved library; reserved identities cannot change.

  • resource_policy is a trusted application policy whose read and parse own every resource read, including includes and external references. A compact resource uses only the policy’s read admission; its XML parse is never called for compact bytes. xml_policy and xml_limits configure XML parsing only without a policy and cannot be combined with one; together with a compact root they are rejected before input is read.

  • limits bounds schema-side compiler work. None leaves every budget unlimited; exhaustion of a work budget raises RelaxNGLimitError. A configured max_diagnostics only bounds report retention, further tightening any policy report bound: beyond it, findings stay counted but are not retained, so suppressed_count exposes the incomplete report and diagnostics_complete is false. max_compact_tokens is cumulative across the root and every nested compact resource, and max_compact_depth is a high-water observation. Truncation never raises a limit error or removes an invalid verdict.

Grammatical errors are recorded on report instead of raising. A malformed compact root raises RelaxNGCompactSyntaxError; a malformed nested compact resource is a schema finding at its exact location. Unreadable or malformed input and unsupported capabilities raise PyXSDError or a more specific PyXSDError subclass.

Parameters:
Return type:

RelaxNGSchema

property projection: pyxsd.relaxng.projection.ProjectionPlan

The immutable schema-static route graph shared by typed adapters.

Compilation materializes this plan after successful correctness checks. The cached property preserves the existing schema constructor signature; directly constructed schemas use the same checked entry condition.

Return type:

pyxsd.relaxng.projection.ProjectionPlan

property projection_classes: pyxsd.relaxng.binding.ProjectionClassFactory

The generated-class factory for this schema’s finite route plan.

One factory per compiled schema preserves class identity across repeated parses, capture settings, and recursive instance depths. Separate schemas own separate class objects even for equivalent plans.

Return type:

pyxsd.relaxng.binding.ProjectionClassFactory

property dependencies: tuple[pyxsd.relaxng.resources.ResourceDependency, ...]

The complete canonical resource closure of the compilation.

Return type:

tuple[pyxsd.relaxng.resources.ResourceDependency, …]

stub(*, compact=False, component_ids=None, depth=None)

Return typing-stub text for this schema’s runtime projection classes.

The full form is an importable-quality .pyi document containing one class block per stable projection route, generic-route comments, and start aliases. compact=True selects the deterministic agent view: a two-line header with an alias legend, one line per class and member, and a trailing start line.

component_ids selects RELAX NG introspection component IDs; depth bounds their outgoing uses dependencies (None follows every reachable component). Only selected route components can become classes, so a definition or pattern ID is an inventory seed rather than a class. An empty selection emits no classes or aliases. Unknown IDs raise KeyError and negative depths raise ValueError.

Emitting never requires a valid schema report and never calls require_valid(); a schema with compilation errors emits a deterministic explanatory comment and its projection plan is not consulted. Selection does not mutate the schema.

Parameters:
Return type:

str

require_valid()

Raise ValidationError when compilation failed.

Return type:

None

iter_parse(sources, *, errors='raise')

Lazily parse explicit local sources with this compiled schema.

This is the same sequential batch orchestration as pyxsd.Schema.iter_parse(): the schema is checked before the first input is pulled, each input is parsed only when requested, expected I/O and malformed-XML failures are isolated in report mode and stop the batch with pyxsd.batch.BatchParseError in raise mode, duplicate source IDs are rejected, and files are closed before an outcome is yielded. Documents are validation-only RELAX NG documents, so each item is parsed with typed=False.

Parsing one schema remains non-reentrant, but the guard covers each item parse rather than the yield boundary: a yielded document may revalidate while the batch stays open.

Parameters:
Return type:

collections.abc.Iterator[pyxsd.batch.ParseOutcome]

parse(xml, *, xml_policy=None, xml_limits=None, typed=True, capture='none', capture_xdm=False, limits=None)

Parse one instance document into the generic RELAX NG tree.

  • xml accepts a path, a readable text/binary stream, or a pre-parsed Element at the caller-trusted boundary, matching pyxsd.Schema.parse(). Malformed or unreadable input raises PyXSDError; grammar mismatches return a document with instance findings.

  • xml_policy and xml_limits configure this instance parse only. A pre-parsed Element is a trusted value, so parser options do not apply to it. A schema compiled with a trusted ResourcePolicy reads and parses instances through that policy instead; combining the two is rejected before input is read.

  • typed defaults to True. A valid typed document receives complete binding evidence and exposes scalar_value() and attribute_value() on the lexical tree; stable routes use their generated projection class, while a route with a semantic fallback and every descendant without a unique route stay generic. No instance value chooses a class layout. typed=False remains evidence-free validation-only parsing and rejects typed access explicitly. Typed parsing never changes the boolean verdict.

  • capture is "none" by default. "patterns" is accepted with typed=True as the setting for an optional, parse-scoped annotation table; capture="patterns", typed=False is rejected with ValueError before any input is read. Other values are rejected the same way. The independent max_capture_entries budget truncates only that table, visibly and without raising; capture settings never truncate mandatory scalar evidence. Table materialization is lazy: parsing succeeds whenever capture="none" does, and a declared datatype decoder failure surfaces only when document.annotations is requested.

  • capture_xdm retains the existing opt-in XDM meaning: the same source revision also becomes an unannotated XML-tree view. A pre-parsed Element is captured structurally, without source bytes or spans. Per-element bindings recorded in the schema’s namespace context are used for both validation and capture. RelaxNGDocument.revalidate replays this request against its reparsed clone, including after a transformed-root wrapper dropped the stale capture object, so the fresh document captures its own current revision.

  • limits bounds this instance’s derivative and evidence work. None uses the compiled schema’s limits. Supplying a RelaxNGLimits replaces that declaration for this parse, and each None field in it means unlimited rather than inheriting the schema value; callers preserving selected schema defaults can pass dataclasses.replace(schema.limits, max_memo_entries=...). The schema value is never modified. Exhaustion raises RelaxNGLimitError instead of reporting invalidity. A configured max_diagnostics only bounds finding retention; suppressed findings stay counted, the report stays invalid, and diagnostics_complete becomes false.

One schema must not parse concurrently or reentrantly. A parse sets a non-blocking guard before input is consumed and clears it on every exit path, including malformed input, limit exhaustion, and generator close. A competing parse raises RuntimeError immediately instead of waiting; separate schema objects remain independent.

The schema report’s errors are rejected before instance input is consumed. Every successful call returns a fresh document report: frozen schema-phase issue objects followed by this parse’s instance findings. Instance findings cover every independent recovery case in source order; recovered states never make the document valid.

Parameters:
Return type:

pyxsd.relaxng.document.RelaxNGDocument

from_data(data, *, format='pyxsd-json', element=None, namespaces=None, fidelity='strict')

Build and validate a document from JSON-compatible data.

The data is converted to a deterministic Clark-named ElementTree with one recorded datatype context per constructed element, then parsed by the ordinary guarded instance path with typed=True, default capture, and no XDM. Conversion problems (malformed shape, wrong containers, duplicate expanded names, bare null, malformed tags, or an ambiguous root) raise PyXSDError before validation; lexically invalid content lands on the returned document’s report exactly as for XML input.

  • format selects one of the five published data formats.

  • element optionally names the root with a local, Clark, or EQName spelling. Root-absorbed formats require it when the start pattern admits more than one name; otherwise it only narrows and confirms.

  • namespaces seeds the root’s inherited prefix frame. In-band declarations and scalar-tag contexts shadow it per element.

  • fidelity selects strict loss rejection or the documented best-effort fallbacks. An unknown value raises ValueError.

Parameters:
  • data (pyxsd.data_conversion.contracts.JsonValue)

  • format (pyxsd.data_conversion.contracts.FormatName)

  • element (str | None)

  • namespaces (collections.abc.Mapping[str, str] | None)

  • fidelity (pyxsd.data_conversion.contracts.Fidelity)

Return type:

pyxsd.relaxng.document.RelaxNGDocument

from_json(source, *, format='pyxsd-json', element=None, namespaces=None, fidelity='strict')

Parse JSON text or UTF-8 bytes and bind it like from_data().

source is JSON content, not a path. The format and fidelity names are validated before the JSON is parsed, and duplicate object keys and the non-standard NaN/Infinity constants are rejected through the shared JSON boundary. The remaining options and error behavior match from_data().

Parameters:
Return type:

pyxsd.relaxng.document.RelaxNGDocument

json_schema(*, format='pyxsd-json', element=None, fidelity='strict', typed=True, always_list=False)

Describe this schema’s JSON data contract as Draft 2020-12 JSON Schema.

The generated schema matches what from_data() accepts and RelaxNGDocument.to_data() produces for the selected format, so every export from a valid, current revision validates against it. It is a structural description, never full RELAX NG validation: grammar validity, name classes, datatype contexts, candidate identity, and unexpressed ordering are listed under x-pyxsd-validation.unvalidated.

  • format - the data-format contract; the RELAX NG profile describes "pyxsd-json" and advertises x-pyxsd-profile: "relaxng".

  • element - an optional local, Clark, or EQName spelling that narrows the start name class; None describes every admitted root name, keeping an open class symbolic.

  • fidelity - "strict" or "best-effort" representation handling; an unknown value raises ValueError.

  • typed / always_list - native-only export options; they must keep their defaults for every other format.

Parameters:
  • format (pyxsd.data_conversion.contracts.FormatName)

  • element (str | None)

  • fidelity (pyxsd.data_conversion.contracts.Fidelity)

  • typed (bool)

  • always_list (bool)

Return type:

dict[str, object]

pyxsd.relaxng.compile
class pyxsd.relaxng.RelaxNGElement

The lexical node used by RELAX NG documents and their projections.

Typed scalar and attribute access requires a typed parse and returns None when no interpretation is available at that position. An invalid typed document raises ValidationError; edits make the interpretation stale and raise StaleInterpretationError on typed access.

classmethod from_etree(element, *, namespaces=None, base_uri=None, source=None)

Build a RELAX NG lexical tree, accepting authored origins as source links.

Parameters:
Return type:

Self

assign_fields(fields, *, selections=())

Encode and apply one atomic transaction from a field mapping.

This is the collision-safe entry point: every key is resolved as a generated projection alias or the route’s scalar descriptor name, so an XML field named assign, assign_fields, or selections cannot shadow the transaction API. Every value is shape-checked, encoded from the plan’s compile-time patterns, and context-checked before any lexical store changes. A successful write dirties the whole revision but never certifies document validity or refreshes typed evidence.

Parameters:
Return type:

None

assign(*, selections=(), **fields)

Convenience keyword form of assign_fields().

Field aliases are reserved away from assign and assign_fields; use assign_fields() for a field whose alias is literally selections so the mapping key is not confused with this keyword.

Parameters:
Return type:

None

class pyxsd.relaxng.AlternativeValue

One immutable, non-preferential scalar interpretation snapshot.

lexical: str
candidates: tuple[Candidate, ...]
context: pyxsd.relaxng.datatypes.DatatypeContext
grammar_fingerprint: str
revision: int
interpretations: tuple[ListInterpretation, ...] = ()
document_evidence: bool = False
as_type(selector)

Decode the one surviving atomic datatype selected by selector.

"xsd:name" means the RELAX NG XSD datatype-library URI, never an instance prefix binding; a tuple selects an explicit (library_uri, type_name). Several distinct matching contracts require as_candidate().

Parameters:

selector (pyxsd.relaxng.datatypes.DatatypeSelector)

Return type:

Any

as_candidate(candidate_id)

Decode the candidate with exactly candidate_id.

Parameters:

candidate_id (str)

Return type:

Any

as_interpretation(candidate_id)

Return the list interpretation attached to candidate_id.

Parameters:

candidate_id (str)

Return type:

ListInterpretation

as_python()

Return the only decodable candidate’s Python value, or fail explicitly.

Return type:

Any

class pyxsd.relaxng.ListInterpretation

One whole-list contract with correlated token assignment evidence.

token_candidates is a per-token marginal view, not a product: choosing one candidate at each position is only legal when the retained list derivation graph contains a complete assignment using them. as_types performs that whole-assignment check. as_python returns a value only when exactly one complete decodable interpretation survives; equal Python values from distinct contracts are never merged.

shape is the schema-static typing classification. tuple and list are ordinary typed results when every token decodes; any other arrangement keeps this interpretation object so callers can inspect token alternatives instead of receiving an invented value. An empty permitted list is a valid interpretation with no token groups, never a failure.

lexical: str
token_spans: tuple[pyxsd.relaxng.validator.TokenSpan, ...]
token_candidates: tuple[tuple[Candidate, ...], ...]
context: pyxsd.relaxng.datatypes.DatatypeContext
grammar_fingerprint: str
revision: int
contract: pyxsd.relaxng.contracts.ScalarContract
candidate_id: str
shape: pyxsd.relaxng.contracts.ListShape
constraints: pyxsd.relaxng.evidence.TokenConstraintGraph
property is_plain: bool

Whether this is a statically plain, completely decodable list.

Return type:

bool

as_python()

Return the only complete decodable interpretation, or fail explicitly.

Return type:

tuple[Any, …] | list[Any]

as_types(selectors)

Decode one datatype selector per token after a whole-assignment check.

A selector names the atomic datatype expected at that token position. Per-token existence is insufficient: the selected contracts must occur together in a complete retained list derivation. The check reuses the compact constraint graph, so it never enumerates token assignments.

Parameters:

selectors (tuple[pyxsd.relaxng.datatypes.DatatypeSelector, ...])

Return type:

tuple[Any, …]