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¶
No single scalar interpretation is authoritative for a position. |
|
A compact-syntax source could not be read into a schema. |
|
A configured RELAX NG budget was exhausted. |
|
A retained interpretation belongs to an older schema revision. |
Classes¶
Immutable annotation view for one lexical element occurrence. |
|
One typed scalar position on a lexical element. |
|
One RELAX NG parse revision with its fresh merged report. |
|
Require one contract candidate at one exact parse occurrence. |
|
One immutable component of a compiled RELAX NG grammar. |
|
A deterministic grammar inventory. |
|
Optional budgets for pattern-graph, evidence, capture, and diagnostics. |
|
An immutable compiled RELAX NG 1.0 schema. |
|
The lexical node used by RELAX NG documents and their projections. |
|
One immutable, non-preferential scalar interpretation snapshot. |
|
One whole-list contract with correlated token assignment evidence. |
Functions¶
|
Return one exact component, raising |
|
Return the immutable grammar inventory, valid schema or not. |
|
Filter by literal case-insensitive text, component kind, and namespace. |
|
Breadth-first component traversal, excluding the seed and duplicates. |
Package Contents¶
- class pyxsd.relaxng.NodeAnnotations¶
Immutable annotation view for one lexical element occurrence.
patternsis the sorted union of surviving authored origins at every scalar and structural site of this element.definitionsnames the compiled grammar definitions whose origins intersect those surviving origins.scalarretains the deterministic typed scalar sites. There is deliberately no singular matched pattern or type.- scalar: tuple[ScalarAnnotation, ...]¶
- class pyxsd.relaxng.ScalarAnnotation¶
One typed scalar position on a lexical element.
kind="text"identifies character data at acontent_indexin the element’s ordered content, including child tails;kind="attribute"identifies one present attribute by its expanded name.valueretains every surviving candidate; the annotation never selects a preferred branch.- kind: Literal['text', 'attribute']¶
- 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.
typedrecords whether this parse requested typed access.interpretations_currentreports whether the recorded validation and evidence snapshot still belongs to the current, unedited lexical revision.binding_evidenceis the immutable evidence graph for a valid typed document, orNonefor validation-only and invalid typed documents.annotationsis the immutable pattern-annotation table for a valid typed parse requested withcapture="patterns", materialized lazily on first access, and raises an explicit capability error when capture did not run.root,report, andsourcekeep the lexical tree, the merged schema/instance report, and the original caller source respectively.- Parameters:
schema (pyxsd.relaxng.schema.RelaxNGSchema)
source (Any)
report (pyxsd.validation.ValidationReport)
typed (bool)
capture (str)
limits (pyxsd.relaxng.limits.RelaxNGLimits | None)
namespace_context (Any)
declarations (pyxsd.dtd_declarations.DocumentDeclarations | None)
xdm_capture (Any)
interpretations_current (bool)
attribute_snapshot (_AttributeSnapshot | None)
binding_evidence (pyxsd.relaxng.evidence.EvidenceGraph | None)
annotations (pyxsd.relaxng.annotations.AnnotationTable | pyxsd.relaxng.annotations.AnnotationCapture | None)
- 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
Nonefor 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:
- 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 raisesValidationErrorwith its report, and an edited or transformed revision raisesStaleInterpretationErrorbefore 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
pyxsdraw Python values.The RELAX NG adapter owns the grouped representation;
typed=Truekeeps Python wrappers and raw scalar values, whiletyped=Falsereads lexical text. Typed export requires a valid document whose evidence still describes this lexical revision.typed=Falseremains a lexical escape path for dirty and invalid trees. The adapter receivesmode="raw"; none of its values are JSON-encoded.
- 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.typedandalways_listare native-only options, rejected exactly as the XSD document rejects them on another format. Typed schema-directed output requires a valid, current typed document; nativetyped=Falseand JsonML remain lexical escapes over the current tree. The adapter receivesmode="json-safe"for JSON-safe scalar output and later tagging.
- 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=Falseinstead of emitting a non-JSON token.
- 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:
- 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/writeremain available on the old document and on the result;to_dict,to_data, andto_jsondispatch 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:
- 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:
- 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.
locationis the exact source occurrence when known,founddescribes the offending token, andexpectedlists the tokens that would have been accepted. The string form starts withsource:line:columnwhen span evidence is available.- Parameters:
message (str)
location (pyxsd.locations.IssueLocation | None)
found (str | None)
- property location: pyxsd.locations.IssueLocation | None¶
The source occurrence where the failure was detected.
- Return type:
- 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_depthbudget even when that budget is unset or larger, anddetailexplains that effective bound.- property budget: str¶
The
RelaxNGLimitsfield name.- Return type:
- 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¶
- class pyxsd.relaxng.RelaxNGComponentDescription¶
One immutable component of a compiled RELAX NG grammar.
kindisgrammar,define,pattern,name-class,datatype,route, orresource.namespaceis an expanded-name namespace only (never a datatype-library URI).nameis 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’snameis the composer-generated key.syntheticis true only for these generated definitions, not for patterns or routes; authoreddefinenames survive only as origins.owner_idisNonefor the grammar and"grammar"for all other components: it denotes inventory ownership, not an authored parent.name_classis 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: noglobal_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.- location: pyxsd.locations.IssueLocation | None¶
- origins: pyxsd.relaxng.origins.OriginTable¶
- class pyxsd.relaxng.RelaxNGSchemaDescription¶
A deterministic grammar inventory.
start_idsnames the compiled start pattern component. Components are sorted by kind rank and then ID;dependenciesis the compilation’s canonical resource closure verbatim, including every dependency record whose content merges into one resource component.- components: tuple[RelaxNGComponentDescription, ...]¶
- pyxsd.relaxng.describe_component(schema, component_id)¶
Return one exact component, raising
KeyErrorfor any other ID.- Parameters:
schema (pyxsd.relaxng.schema.RelaxNGSchema)
component_id (str)
- Return type:
- 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:
- pyxsd.relaxng.find_components(schema, *, text=None, kind=None, namespace=None)¶
Filter by literal case-insensitive text, component kind, and namespace.
Noneleaves 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:
schema (pyxsd.relaxng.schema.RelaxNGSchema)
text (str | None)
kind (str | None)
namespace (str | None)
- Return type:
Breadth-first component traversal, excluding the seed and duplicates.
- Parameters:
schema (pyxsd.relaxng.schema.RelaxNGSchema)
component_id (str)
direction (Literal['uses', 'used_by'])
depth (int)
- Return type:
- 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_entriesbounds the independent optional annotation table and truncates it visibly instead of raising. Amax_diagnosticsbudget is a truncatable retention budget, not a work budget.max_compact_tokenscharges emitted compact tokens cumulatively;max_compact_depthchecks 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 leakRecursionError. The compiler’s graph and semantic correctness checks run regardless of these values; a projection budget never skips a correctness check.
- class pyxsd.relaxng.RelaxNGSchema¶
An immutable compiled RELAX NG 1.0 schema.
reportholds the merged reader, simplification, composition, and correctness findings of this compilation.grammaris the composed semantic graph with every reference bound; itsstartmay be aRefedge whosetargetis the root element pattern.dependenciesis the complete canonical resource closure, andnamespace_contextis the root resource’s namespace context, keeping the authored root frame exactly (an undeclared default namespace remains an empty entry).limitsis the schema’s effective budget declaration (unlimited when none was supplied), anddatatype_fingerprintidentifies 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.
- grammar: pyxsd.relaxng.simplify.CompiledGrammar¶
- namespace_context: pyxsd.namespaces.NamespaceContext¶
- 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.
sourceis a local path or a readable text/binary stream. Remote resources require an authorizingResourcePolicy; an already-parsedElementis deliberately not accepted because it cannot carry policy parser evidence.syntaxselects 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_librariesmaps library URIs to application registrations. It augments the built-in and XSD libraries and may replace a nonreserved library; reserved identities cannot change.resource_policyis a trusted application policy whosereadandparseown every resource read, including includes and external references. A compact resource uses only the policy’sreadadmission; its XMLparseis never called for compact bytes.xml_policyandxml_limitsconfigure XML parsing only without a policy and cannot be combined with one; together with a compact root they are rejected before input is read.limitsbounds schema-side compiler work.Noneleaves every budget unlimited; exhaustion of a work budget raisesRelaxNGLimitError. A configuredmax_diagnosticsonly bounds report retention, further tightening any policy report bound: beyond it, findings stay counted but are not retained, sosuppressed_countexposes the incomplete report anddiagnostics_completeis false.max_compact_tokensis cumulative across the root and every nested compact resource, andmax_compact_depthis a high-water observation. Truncation never raises a limit error or removes an invalid verdict.
Grammatical errors are recorded on
reportinstead of raising. A malformed compact root raisesRelaxNGCompactSyntaxError; a malformed nested compact resource is a schema finding at its exact location. Unreadable or malformed input and unsupported capabilities raisePyXSDErroror a more specificPyXSDErrorsubclass.- Parameters:
source (pyxsd.relaxng.resources.ResourceSource)
syntax (pyxsd.relaxng.readers.SchemaSyntax)
datatype_libraries (collections.abc.Mapping[str, pyxsd.relaxng.datatypes.DatatypeLibraryRegistration] | None)
resource_policy (pyxsd.resource_policy.ResourcePolicy | None)
xml_policy (pyxsd.xml_policy.XmlParserPolicy | None)
xml_limits (pyxsd.xml_policy.XmlLimits | None)
limits (pyxsd.relaxng.limits.RelaxNGLimits | None)
- Return type:
- 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
.pyidocument containing one class block per stable projection route, generic-route comments, and start aliases.compact=Trueselects the deterministic agent view: a two-line header with an alias legend, one line per class and member, and a trailing start line.component_idsselects RELAX NG introspection component IDs;depthbounds their outgoingusesdependencies (Nonefollows every reachable component). Only selectedroutecomponents 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 raiseKeyErrorand negative depths raiseValueError.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.
- require_valid()¶
Raise
ValidationErrorwhen 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 withpyxsd.batch.BatchParseErrorin 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 withtyped=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:
sources (collections.abc.Iterable[pyxsd.batch.DocumentSource])
errors (Literal['raise', 'report'])
- Return type:
- 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.
xmlaccepts a path, a readable text/binary stream, or a pre-parsedElementat the caller-trusted boundary, matchingpyxsd.Schema.parse(). Malformed or unreadable input raisesPyXSDError; grammar mismatches return a document with instance findings.xml_policyandxml_limitsconfigure this instance parse only. A pre-parsedElementis a trusted value, so parser options do not apply to it. A schema compiled with a trustedResourcePolicyreads and parses instances through that policy instead; combining the two is rejected before input is read.typeddefaults toTrue. A valid typed document receives complete binding evidence and exposesscalar_value()andattribute_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=Falseremains evidence-free validation-only parsing and rejects typed access explicitly. Typed parsing never changes the boolean verdict.captureis"none"by default."patterns"is accepted withtyped=Trueas the setting for an optional, parse-scoped annotation table;capture="patterns", typed=Falseis rejected withValueErrorbefore any input is read. Other values are rejected the same way. The independentmax_capture_entriesbudget truncates only that table, visibly and without raising; capture settings never truncate mandatory scalar evidence. Table materialization is lazy: parsing succeeds whenevercapture="none"does, and a declared datatype decoder failure surfaces only whendocument.annotationsis requested.capture_xdmretains the existing opt-in XDM meaning: the same source revision also becomes an unannotated XML-tree view. A pre-parsedElementis 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.revalidatereplays 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.limitsbounds this instance’s derivative and evidence work.Noneuses the compiled schema’s limits. Supplying aRelaxNGLimitsreplaces that declaration for this parse, and eachNonefield in it means unlimited rather than inheriting the schema value; callers preserving selected schema defaults can passdataclasses.replace(schema.limits, max_memo_entries=...). The schema value is never modified. Exhaustion raisesRelaxNGLimitErrorinstead of reporting invalidity. A configuredmax_diagnosticsonly bounds finding retention; suppressed findings stay counted, the report stays invalid, anddiagnostics_completebecomes 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
RuntimeErrorimmediately 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:
xml (str | pathlib.Path | os.PathLike[str] | IO[str] | IO[bytes] | xml.etree.ElementTree.Element)
xml_policy (pyxsd.xml_policy.XmlParserPolicy | None)
xml_limits (pyxsd.xml_policy.XmlLimits | None)
typed (bool)
capture (str)
capture_xdm (bool)
limits (pyxsd.relaxng.limits.RelaxNGLimits | None)
- Return type:
- 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) raisePyXSDErrorbefore validation; lexically invalid content lands on the returned document’s report exactly as for XML input.formatselects one of the five published data formats.elementoptionally 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.namespacesseeds the root’s inherited prefix frame. In-band declarations and scalar-tag contexts shadow it per element.fidelityselects strict loss rejection or the documented best-effort fallbacks. An unknown value raisesValueError.
- 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:
- 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/Infinityconstants are rejected through the shared JSON boundary. The remaining options and error behavior matchfrom_data().- Parameters:
- Return type:
- 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 andRelaxNGDocument.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 underx-pyxsd-validation.unvalidated.format- the data-format contract; the RELAX NG profile describes"pyxsd-json"and advertisesx-pyxsd-profile: "relaxng".element- an optional local, Clark, or EQName spelling that narrows the start name class;Nonedescribes every admitted root name, keeping an open class symbolic.fidelity-"strict"or"best-effort"representation handling; an unknown value raisesValueError.typed/always_list- native-only export options; they must keep their defaults for every other format.
- 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
Nonewhen no interpretation is available at that position. An invalid typed document raisesValidationError; edits make the interpretation stale and raiseStaleInterpretationErroron 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:
element (xml.etree.ElementTree.Element)
namespaces (pyxsd.namespaces.NamespaceContext | None)
base_uri (str | None)
source (pyxsd.locations.IssueLocation | pyxsd.relaxng.origins.SourceOrigin | None)
- 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, orselectionscannot 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:
fields (collections.abc.Mapping[str, object])
selections (tuple[pyxsd.relaxng.evidence.CandidateSelection, ...])
- Return type:
None
- assign(*, selections=(), **fields)¶
Convenience keyword form of
assign_fields().Field aliases are reserved away from
assignandassign_fields; useassign_fields()for a field whose alias is literallyselectionsso the mapping key is not confused with this keyword.- Parameters:
selections (tuple[pyxsd.relaxng.evidence.CandidateSelection, ...])
fields (Any)
- Return type:
None
- class pyxsd.relaxng.AlternativeValue¶
One immutable, non-preferential scalar interpretation snapshot.
- interpretations: tuple[ListInterpretation, ...] = ()¶
- 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 requireas_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:
- 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_candidatesis 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_typesperforms that whole-assignment check.as_pythonreturns a value only when exactly one complete decodable interpretation survives; equal Python values from distinct contracts are never merged.shapeis the schema-static typing classification.tupleandlistare 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.- contract: pyxsd.relaxng.contracts.ScalarContract¶
- 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:
- as_python()¶
Return the only complete decodable interpretation, or fail explicitly.
- 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, …]