pyxsd¶
XML schema processing in Python.
XSD and RELAX NG bindings, Schematron validation, and schema-aware XSLT.
Submodules¶
Public exports¶
- pyxsd.AddressResolver(*args, **kwargs)¶
- class pyxsd.BindingPolicy(invalid_value='drop', unresolved_type='error', undeclared_content='error', whitespace='xsd', namespaces='strict', facets='strict')¶
How instance binding behaves when a document is not strictly valid.
invalid_value- for an element whose lexical value does not validate:"drop"bindsNone(each type’s “unvalidated” stand-in);"raw"binds the original text as a plain string so no data is lost.unresolved_type- when an element’s declared type cannot be resolved:"error"records the problem and drops the subtree;"generic"records the problem too, but also binds the subtree through the wildcard pass-through path.undeclared_content- elements that no content-model particle accepts:"error"records the problem;"generic"also binds them generically so unrecognized markup survives.whitespace-"xsd"applies XSD 1.0 whitespace processing (space/tab/CR/LF only);"compat"additionally folds other Unicode whitespace (for example NBSP) the way Python’s ownstr.stripdoes.namespaces-"strict"resolves QNames, keys components by expanded name, and matches instances namespace-correctly;"legacy"matches elements and attributes by local name, discarding the namespace URI."legacy"is the explicit compatibility choice for documents that match by local name alone.facets-"strict"enforces the XSD facets declared on simple types (enumeration,pattern,lengthand the other length facets,minInclusive/maxInclusiveand their exclusive pairs,totalDigits/fractionDigits, andwhiteSpace) while binding."off"skips facet enforcement for callers who want schema-guided mapping without a strict validation verdict; the report then no longer answers “is this document valid?” for facet-constrained values.
- Parameters:
- class pyxsd.Document(schema, root, source, report, *, provenance=None, declarations=None, xdm_capture=None)¶
A schema-bound instance document: the interaction hub.
schemaisNonefor a schemaless document. Schema-dependent operations such asrevalidate()reject that case explicitly; traversal, XPath, writing, and the native exports still operate on the document’s root.- Parameters:
schema (Schema | None)
root (Any)
source (str | Path | os.PathLike[str] | IO[str] | ET.Element | None)
report (ValidationReport)
provenance (ParseProvenance | None)
declarations (DocumentDeclarations | None)
xdm_capture (Any)
- schema: Schema | None¶
The schema the document was parsed against, or
Nonewhen the document is schemaless.
- root: Any¶
The bound root instance, or
Nonewhen binding failed (for example an unknown document root element).
- source: str | Path | os.PathLike[str] | IO[str] | ET.Element | None¶
The source the document was parsed from, as given to
parse.
- locate(location)¶
Resolve a source occurrence in this parse, not by value or local name.
Addresses are parse-revision-specific. Manually built/transformed Documents have no provenance until freshly parsed with revalidate(). Attribute lookups return the original lexical attribute value.
- Parameters:
location (IssueLocation)
- Return type:
- property report: ValidationReport¶
schema-phase issues, then instance-phase.
- Type:
The merged report
- require_valid()¶
Raises
pyxsd.ValidationErrorif the report has errors.- Return type:
None
- write(dest)¶
Writes the bound tree to dest (a path or a file object).
- to_xdm()¶
Returns the coherent XDM view captured by this parse.
Capture is opt-in: the document must have been parsed with
Schema.parse(..., capture_xdm=True). For a path or readable stream the returned tree is source-complete (comments, processing instructions, namespace declarations, and occurrence annotations survive) and immutable. XSD capture of a pre-parsedElementuses its ElementTree serialization. RELAX NG captures a pre-parsedElementstructurally, without source bytes or spans. A text stream is normalized to UTF-8 with the declaration encoding rewritten to match the bytes. If the bound tree was edited, replaced, or built by the caller, this raisesXdmInputErrorinstead of returning a view that disagrees with the document.- Return type:
- to_dict(*, typed=True, always_list=False)¶
Returns the bound tree as a plain dict with raw Python scalars.
The export convention (child element keys,
@attributes, the$text key, repeated children as lists) is documented indocs/data-model.md. For an element whose content admits character data (mixed content,xs:anyType, wildcard pass-through),$holds all of its recorded character data in document order: the leading text followed by every child’s_tail_, concatenated. The dict shape cannot represent text/element interleaving;to_string()andxpath()are the faithful mixed-content views.This is the raw native interface: typed values remain the bound XSD scalar objects.
to_data()is its JSON-safe counterpart.
- to_data(*, format='pyxsd', fidelity='best-effort', typed=True, always_list=False)¶
Returns the bound tree under an explicit JSON data contract.
format="pyxsd"keeps the nativeto_dict()structure and converts its scalars to JSON-safe values.format="pyxsd-json"uses the compiled schema’s layout and the root-preservingQ{uri}localprofile.typedandalways_listare native-only options; another format rejects a non-default value withValueError.- Parameters:
format (FormatName)
fidelity (Fidelity)
typed (bool)
always_list (bool)
- Return type:
- to_json(*, indent=None, format='pyxsd', fidelity='best-effort', typed=True, always_list=False)¶
Returns
to_data()encoded as standards-compliant JSON text.No fallback serializer is used: every value is already JSON-safe and non-finite floats use their
INF/-INF/NaNstrings.
- transform(fn, *args, **kwargs)¶
Applies fn to the document.
A
DocumentTransformis dispatched first:fn.transform_document(self)runs the whole document through it and the returned document is passed through unchanged. Document transforms carry their own configuration, so extra call arguments are rejected.Any other callable keeps the legacy root-callable behavior:
fn(root, *args, **kwargs)may return a new tree root, which becomes the root of a new document against the same schema — or anything else, includingNone, which is returned unchanged. The schema-specific node check is the narrow_document_for_node_resulthook: XSD wraps a boundSchemaBaseroot, while RELAX NG wraps its lexicalRelaxNGElementtree. When a transform mutates the tree in place and returnsNone, the original document remains available to the caller; no new document is created.
A returned document shares this document’s report, which reflects the tree as it was parsed, not the transformed shape;
revalidate()is the refresh path.
- revalidate()¶
Re-parses the serialized tree, returning a fresh
Document.The bound tree is written out and parsed again against the same schema, so the returned document carries a fresh instance report for the tree’s current shape (transforms may have changed it). The
sourceis carried over, and so is the original parse’s DTD declaration evidence: serialization drops the DOCTYPE, so rebinding with the recorded evidence keeps a declaredENTITY/ENTITIESvalue valid, while complete evidence still rejects an undeclared replacement value. A document with no evidence (a caller-built tree, a custom policy parse) stays lexical-only instead of inventing an empty declaration set.A plain
Document(schema=None)raisesPyXSDErrorbecause there is no schema to bind against. UseSchemalessDocument.revalidate()to refresh a schemaless document from its current lexical tree.- Return type:
- xpath(expr, *, namespaces=None)¶
Evaluates an XPath expression over the bound tree.
Returns node results as the original bound instances and passes scalar results (numbers, strings, booleans) through. The expression is evaluated with the document’s root element as the context item, so an absolute path starts
/root. namespaces maps query prefixes to namespace URIs.The query runs over a projection of the bound tree, so it sees exactly what the object model holds: descriptor write-through is reflected,
textmirrors_value_and a child’stailmirrors its recorded_tail_, so mixed character data is queryable in document order. Parsing does not preserve comment nodes, and an element with_value_ is Noneprojectstext=None. The projection is document-faithful, not source-XPath-exact: element-only content’s recorded layout whitespace (the tails between block children) is part of the text a value query returns. Seedocs/data-model.md.
- class pyxsd.Extensions¶
A per-compile registry of mixin selectors.
Each registration method may be used as a decorator (
@ext.for_type(...)), which registers the decorated class and returns it, or called directly (ext.for_type(name, mixin=Cls)). Everyfor_*selector compiles to a predicate over the type ER immediately;for_pathis stored raw for later resolution.Registration order is precedence: a later registration outranks an earlier one, so
mixins_for()lists the most recently registered match first. Instances are standalone — no global registry state.- for_type(name, mixin=None)¶
Registers mixin for a type by name.
name is a plain local name (
"Code") or a Clark name ("{uri}Code"). Withoutmixin, returns a decorator that registers the decorated class.
- for_namespace(uri, mixin=None)¶
Registers mixin for every type declared in namespace uri.
An empty or
Noneuri selects declarations that have no namespace.
- for_kind(kind, *, derived_from=None, mixin=None)¶
Registers mixin for types of kind (
simpleTypeorcomplexType).With derived_from, only types whose
superClassNameslist the given base (matched by local or expanded spelling) qualify.
- for_path(path, mixin=None)¶
Registers mixin for the type of the element at an instance path.
path names element declarations from the document root down (
"/ClinicalDocument/recordTarget/patient"); every segment is a local element name. The final segment’s declaration contributes the selected type — its inline anonymous type when one is declared, else the referenced global type — matched later by ER identity, never by the anonymous type’s synthesized (and collidable) name. Resolution happens at class-building time against the composed declaration tree; a segment matching no declaration fails the compile loudly. Traversal stays within each element’s own content model — the base chain of an extension-typed element is not followed, so a segment naming a base-declared child dangles loudly too.
- where(predicate, mixin=None)¶
Registers mixin for every type ER satisfying predicate.
- mixins_for(er, schema=None)¶
The mixins matching the type ER er, in precedence order.
The first element is the highest-precedence (most recently registered) match; a mixin registered by several matching selectors appears once, at its highest-precedence position.
Raw path entries resolve against the owning schema ER’s composed declaration tree — class building happens after schema composition, so the tree is complete then — once per compile (the resolutions are cached per schema, and a registry reused across compiles resolves the same path again against each new tree). Without schema (an ER-tree-only caller) path entries stay skipped and silent.
- class pyxsd.HttpClientTransport(*, clock=<built-in function monotonic>)¶
The stdlib HTTPS transport used when a policy opts into remote access.
Each call creates a fresh default TLS context (certificate and hostname verification enabled), connects with at most
connect_timeout, then reads the response through a deadline-aware socket proxy. Every low-level socket read, including the status line, each header line, chunk framing, and body data, re-arms the timeout to the smaller ofread_timeoutand the time left beforerequest_seconds. The deadline therefore covers connecting, the response headers, and all body reads, so a server that drips bytes cannot hold the request open indefinitely.Content-Lengthis never trusted; a response whose streamed bytes exceed the budget is rejected. The response and connection are closed on every outcome.Failures that leave no usable response raise
RemoteTransportError: a non-HTTPS URL, a missing host or invalid port, an oversized response, a malformed HTTP response, or an expiredrequest_secondsdeadline. DNS, TLS, and socket failures (including a read timeout shorter than the remaining deadline) propagate as the originalOSErrorsubclass. Either way the connection is already closed when the exception escapes.- Parameters:
clock (Callable[[], float])
- fetch(url, *, limits)¶
- Parameters:
url (str)
limits (RemoteLimits)
- Return type:
- class pyxsd.NamespaceError¶
A QName used a prefix that is not bound in its scope.
- class pyxsd.ParseModes¶
Named
BindingPolicypresets forSchema.compile.Each attribute is an ordinary policy, so a caller can pass
ParseModes.LAXfor a convenient preset or a hand-builtBindingPolicyfor granular control. New presets belong here; no call signature has to change.- STRICT = BindingPolicy(invalid_value='drop', unresolved_type='error', undeclared_content='error', whitespace='xsd', namespaces='legacy', facets='strict')¶
Strict binding with local-name namespace matching. Kept explicitly for callers that need the pre-namespaced behavior.
- LAX = BindingPolicy(invalid_value='raw', unresolved_type='generic', undeclared_content='generic', whitespace='xsd', namespaces='legacy', facets='strict')¶
Keep the report strict while binding best-effort values. Invalid lexical values become raw strings, and unresolved or undeclared subtrees are bound generically instead of dropped. Kept explicitly for callers that need the pre-namespaced behavior.
- NAMESPACED = BindingPolicy(invalid_value='drop', unresolved_type='error', undeclared_content='error', whitespace='xsd', namespaces='strict', facets='strict')¶
Strict binding plus XSD-correct namespace handling. This is the default policy.
- LAX_NAMESPACED = BindingPolicy(invalid_value='raw', unresolved_type='generic', undeclared_content='generic', whitespace='xsd', namespaces='strict', facets='strict')¶
Lax binding plus XSD-correct namespace handling. Combine with
.replace()for other mixes.
- class pyxsd.PyXSDError¶
Raised when parsing cannot proceed.
- class pyxsd.PyXSDWarning¶
Warning category for recoverable, non-fatal conditions.
- class pyxsd.RemoteLimits(response_bytes=16777216, closure_bytes=134217728, resources=128, depth=16, redirects=5, connect_timeout=10.0, read_timeout=30.0, request_seconds=30.0, xml_depth=256, xml_elements=250000)¶
Finite budgets for remote retrieval and the XML it admits.
response_bytesbounds one downloaded resource andclosure_bytesbounds all resources fetched for one compilation.resourcesanddepthbound the dependency closure,redirectsbounds the hops the caller may authorize, and the three timeouts configure connecting, each socket read, and the total request.xml_depthandxml_elementsare structural limits for the strict parser that consumes a downloaded resource.- Parameters:
- class pyxsd.RemoteResourcePolicy(*, allowed_origins=(), allow_remote_hints=False, allow_local_remote=False, allow_private_addresses=False, limits=None, transport=None, resolver=None)¶
Opt-in HTTPS schema loading with per-compilation budgets and trust rules.
Selecting the policy authorizes the application’s remote root schema. Dependencies of an admitted remote document may reference the same origin as the root or the requesting document; anything else must appear in
allowed_origins. An instancexsi:schemaLocation/xsi:noNamespaceSchemaLocationthat names a remote schema needsallow_remote_hints=Trueas well. A local schema (or anonymous stream) may reference a remote dependency only withallow_local_remote=True.Every remote read is HTTPS, address-checked, and budgeted: one response’s bytes never exceed
limits.response_bytes, the whole closure never exceedslimits.closure_bytes,limits.resourcesunique URLs, andlimits.depthdependency levels. Redirects are followed one request at a time, with the scheme, origin, and addresses revalidated before each new request, up tolimits.redirectshops. Every downloaded body counts towardclosure_bytes, including redirect and error responses, andlimits.redirectsis a closure-wide total across all resources (not a per-resource cap).The main schema of an explicit
pyxsd.compile()is the only root read. An anonymous stream has no root read, so every memory-base dependency is still a local-to-remote dependency and needsallow_local_remote=True; a stream’s document-authored remote reference can never authorize an arbitrary origin as a root or reset the closure budgets.compilation()gives each in-flight compile its own closure state (a context variable), so one policy instance can serve concurrent compiles without sharing origins or budgets. Directreadcalls outside a compilation share one fallback closure and each explicit root read resets it.Pivots are denied: a remote document may never resolve to a local path or a
file:/other non-HTTPS URL, remote instance documents are refused, and a remote schema never loads a Python overlay (a<memory>schema has no local directory for a module-name overlay either).parsealways usesXmlParserPolicy.strict()and the policy’s XML limits (response_bytesfor bytes,xml_depthandxml_elementsfor structure), so a downloaded document declaring a DTD or entity is denied. There is no persistent cache and no external-entity handler.Once this policy is selected, transport and resolver failures abort the compile even for a document-authored
xs:include/xs:import; only the no-policy path keeps the offline advisory missing-resource behavior.resolveris consulted before every request. The transport resolves the hostname again for the connection, so this preconnection check cannot claim DNS-rebinding immunity (see the module docstring).limitsdefaults to a freshRemoteLimits;transportdefaults toHttpClientTransport;resolverdefaults to the system resolver.- Parameters:
allow_remote_hints (bool)
allow_local_remote (bool)
allow_private_addresses (bool)
limits (RemoteLimits)
transport (RemoteTransport | None)
resolver (AddressResolver | None)
- limits: RemoteLimits¶
- compilation(*, root_read=True)¶
Isolate the closure state of one in-flight compilation.
root_readis true when the compilation’s main schema is an explicit path or URL (so the first schema read is the authorized root) and false for an anonymous stream, whose dependencies must still authorize local-to-remote loading. Each entered scope has its own resources, bytes, redirects, depths, and root origin, so concurrent compiles on one policy do not share or reset each other’s budgets.pyxsd.compile()calls this automatically for this policy.
- read(source, *, base, purpose)¶
Read a local resource or an authorized remote schema.
- Parameters:
- Return type:
- parse(data, context)¶
Parse admitted bytes with the strict defused profile and XML limits.
- Parameters:
data (ResourceData)
context (NamespaceContext)
- Return type:
- class pyxsd.RemoteResponse(url, status, headers, content)¶
One HTTP response, bounded and exactly as received.
headerskeeps HTTP field-name case-insensitivity, so a redirect’sLocationis found however the server cased it.
- class pyxsd.RemoteTransport(*args, **kwargs)¶
The retrieval seam a remote resource policy calls one hop at a time.
- fetch(url, *, limits)¶
Perform one HTTPS request without following a redirect.
- Parameters:
url (str)
limits (RemoteLimits)
- Return type:
- class pyxsd.RemoteTransportError¶
A bounded remote fetch failed; no response is available.
- class pyxsd.ResourcePolicy(*args, **kwargs)¶
Application-controlled loading and parsing for a schema and its instances.
Source IDs are canonical strings: a local path (including a virtual path a policy defines, such as
/workspace/...), an absolute remote URI, or<memory>for an anonymous stream. A dependency’s base is its including document, not its directory: a policy resolves a remote base with URI semantics and any other base with its own filesystem semantics.purposeis aResourcePurpose:"schema"for an explicitly supplied schema, a caller’s namespace mapping, and an ordinary schema dependency;"schema-hint"for a schema an instance document selected throughxsi:schemaLocationorxsi:noNamespaceSchemaLocation; and"instance"for an instance document. Parsers must populate the supplied namespace context. Anonymous streams use<memory>and have no implicit filesystem base.- read(source, *, base, purpose)¶
Authorize and read a named resource, retaining its original bytes.
- Parameters:
- Return type:
- parse(data, context)¶
Parse admitted bytes and record namespace evidence.
- Parameters:
data (ResourceData)
context (NamespaceContext)
- Return type:
- class pyxsd.ResourcePolicyError¶
A resource/parser policy refused input; never a missing-resource hint.
- class pyxsd.Schema(classes, components, namespace_context, mode, target_namespace, report, source, schema_context=None)¶
A compiled XML Schema and the classes generated from it.
- Parameters:
- xsd_version: str¶
The XSD processor version this schema was compiled under (“1.0” or “1.1”). It is the declared
Vthatvc:*selectors were tested against; the schema’s own vocabulary is not restricted by it (that is the compiler’s job, seeversion_gates).
- classes: dict[str, type[SchemaBase]]¶
Generated classes keyed by declaration name (bare local names and, where the type has an expanded name, Clark names).
- report: ValidationReport¶
Schema-phase validation issues (composition, declaration, and derivation problems). Instance-phase issues never land here.
- source: str | Path | PathLike[str] | IO[str] | Element | None¶
The source the schema was compiled from, as given to
compile.
- resource_policy: ResourcePolicy | None¶
- declaration_origins: weakref.WeakKeyDictionary[ET.Element, IssueLocation]¶
- classmethod compile(source, *, mode=BindingPolicy(invalid_value='drop', unresolved_type='error', undeclared_content='error', whitespace='xsd', namespaces='strict', facets='strict'), xsd_version='1.1', namespace_schemas=None, overlay=None, namespace_context=None, schema_location_pairs=None, extensions=None, resource_policy=None, xml_policy=None, xml_limits=None, base_uri=None, _source_purpose='schema')¶
Compiles source into a
Schema.source- a schema file path or a file object open for reading, or an already-parsedxml.etree.ElementTree.Elementused as the schema document root directly. An unopenable file, malformed XML, or a document whose root is notxs:schemaraisePyXSDError; schema-legality problems are collected onreportinstead. A caller that supplies anElementalso supplies its namespace evidence onnamespace_context; no serialization or reparse occurs.mode- aBindingPolicy(usually aParseModespreset). Defaults toNAMESPACED.xsd_version- the XSD processor version the document is compiled as,"1.0"or"1.1"(default"1.1"). It is the declared versionvc:*conditional-inclusion selectors test against: in"1.0"mode a declaration carryingvc:minVersion="1.1"is dropped (XSD 1.1 §4.2.2). The vocabulary itself is checked separately (seepyxsd.version_gates).namespace_schemas- an optional{namespace_uri: path}mapping supplying schemas for namespaces referenced byxs:importwithout aschemaLocation.overlay- an optional overlay class file, loaded after class generation (experimental).namespace_context- an existing prefix-to-URI binding context for the schema documents’ bindings to accumulate into, instead of a fresh one (parse()passes the context that already holds the instance’s bindings, so one context accumulates them all).schema_location_pairs- extra(namespace, location)pairs from an instance document’sxsi:schemaLocationbeyond the main schema. Advisory hints: consulted in strict namespace mode only, and one that cannot be loaded is aschema-hintwarning (parse()passes the instance’s pairs; a schema-only compile has none).extensions- an optionalExtensionsregistry selecting mixins to fold into the generated classes’ bases at build time (XsdType. getBaseList). Without one, class generation is unchanged.resource_policy- a trusted application resource policy. Itsparse()owns XML parsing, soxml_policyandxml_limitscannot be combined with it.xml_policy- an opt-inXmlParserPolicyapplied to the main schema and every included/imported dependency.Nonekeeps stdlib parsing and its current DTD/entity behavior. The choice is compile- scoped: it never becomes the default for laterparse()calls.xml_limits- optionalXmlLimitsbyte/depth/element budgets for the same documents.base_uri- the base reference for an already-parsedElement(or a stream with no path), used to resolve relativexs:include/xs:importlocations and to give the resource policy a document base. It is ignored for a path source, whose own location is its base._source_purpose- internal: the resource purpose the main schema document reads under.pyxsd.parse()passes"schema-hint"when the instance’s own location hint selected the schema and"schema"when the caller named it.
Use
require_valid()to reject a schema whose report holds errors.- Parameters:
mode (Any)
xsd_version (Literal['1.0', '1.1'])
namespace_context (NamespaceContext | None)
extensions (Extensions | None)
resource_policy (ResourcePolicy | None)
xml_policy (XmlParserPolicy | None)
xml_limits (XmlLimits | None)
base_uri (str | None)
_source_purpose (Literal['schema', 'schema-hint', 'instance', 'text', 'collection'])
- Return type:
- require_valid()¶
Raises
pyxsd.ValidationErrorif the report has errors.- Return type:
None
- stub(*, compact=False, component_ids=None, depth=None)¶
Returns
.pyi-style source for the classes this schema compiled.The text is a typing surface mirroring the runtime: one class block per generated class, annotated with the classes a valid parsed document actually reads back, and the root elements as module-level class aliases. A member whose type cannot be named truthfully degrades to
Anywith the reason in a comment, never to a name the runtime does not use.compact- emit the agent-oriented compact description instead of the full document: one line per class and member, a short alias legend, and the root elements in a trailing comment. The compact text is a description, not valid Python; the default full form is importable-quality.pyisource:schema.stub() # full .pyi document schema.stub(compact=True) # compact agent-oriented view
The CLI emits the same text:
pyxsd --emit-stubs [PATH] -s SCHEMAwrites the full document to PATH (stdout when PATH is omitted), and adding--stubs-compactselects the compact view.component_idsoptionally selects native declaration IDs, withdepthbounding their outgoing dependencies (None follows all). Unknown IDs raise KeyError and negative depths raise ValueError. Seepyxsd.introspectionfor IDs and declaration metadata.Unfiltered emitting never raises for a schema that compiled and does not require a valid report; call
require_valid()separately to reject a schema whose report holds errors.
- iter_parse(sources, *, errors='raise')¶
Lazily parse explicit local sources using this compiled schema.
On first iteration, require a valid schema before consuming inputs. Default raise mode stops with
pyxsd.batch.BatchParseError; report mode yields invalid documents and expected input failures. Source IDs must be unique. Internal defects always propagate. Do not parse concurrently or reentrantly on this schema.- Parameters:
sources (Iterable[DocumentSource])
errors (Literal['raise', 'report'])
- Return type:
- parse(xml, *, xml_policy=None, xml_limits=None, capture_xdm=False)¶
Binds xml against this schema and returns a
Document.xml- the instance document: a file path, a file object open for reading, or a parsedxml.etree.ElementTree.Elementused as the document root directly. An unopenable file or malformed XML raisesPyXSDError(the fatal-input rule); content problems instead land on the document’s report.xml_policy/xml_limits- opt-in parser posture and structural budgets for this instance parse only. They do not inherit a nondefault policy fromcompile();Nonekeeps stdlib parsing and unlimited structure. They cannot be combined with a customresource_policy, whoseparse()is trusted application code. A pre-parsedElementis also a caller-trusted boundary, so no parser option is applied.capture_xdm- opt-in coherent XDM capture. When true, the same source revision is also parsed into a source-completeXdmDocumentand the document retains an immutable bound-tree snapshot.to_xdm()returns that view and rejects later edits to the bound tree. Paths and readable streams are read to EOF once (short chunks included); the byte budget is enforced on the consumed source before normalization, so an over-limit text stream raises the normal budget error instead of parsing a shortened valid prefix. A reader whoseread()rejects a size argument is read once and its single value is accepted or rejected whole. A text stream is normalized to UTF-8 and its XML declaration encoding is rewritten to match; a pre-parsedElementis captured as its ElementTree serialization, so lexical comments and original prefixes that the tree no longer holds are absent. The default keeps ordinary parsing’s cost and behavior: no XDM state is built or retained. As with ordinary parsing, parses on one schema must not run concurrently or reentrantly.
Each parse binds with its own fresh instance report, so a schema may serve many documents without their findings mixing: the returned document’s
reportmerges this schema’s (frozen) compilation issues with the document’s own binding issues.Document.rootisNonewhen the document root matched no global element declaration (theunknown-rootissue records why).
- from_data(data, *, format='pyxsd-json', element=None, namespaces=None, fidelity='strict')¶
Binds JSON-compatible data through the normal instance parser.
The data is converted to a Clark-named ElementTree with recorded namespace frames and then bound by
parse(), so generated classes, defaults, and the validation report behave exactly as for an XML document. Conversion problems (malformed structure, wrong containers, wrong scalar types, conflicting markers) raisePyXSDErrorbefore binding; content problems land on the returned document’s report.format- the data format contract;"pyxsd-json"is the schema-driven profile this method documents.element- an optional local, Clark, or EQName spelling that selects or confirms the global root.namespaces- an optional prefix-to-URI mapping used as the root’s inherited namespace frame.fidelity-"strict"or"best-effort"representation handling; an unknown value raisesValueError.
- Parameters:
data (bool | int | float | str | list[bool | int | float | str | list[JsonValue] | dict[str, JsonValue] | None] | dict[str, bool | int | float | str | list[JsonValue] | dict[str, JsonValue] | None] | None)
format (Literal['pyxsd', 'pyxsd-json', 'parker', 'badgerfish', 'jsonml'])
element (str | None)
fidelity (Literal['strict', 'best-effort'])
- Return type:
- from_json(source, *, format='pyxsd-json', element=None, namespaces=None, fidelity='strict')¶
Binds JSON text (or UTF-8 bytes) through
from_data().source is JSON content, not a path; callers reading files use
Path.read_text()first. Parsing rejects duplicate object keys and the non-standardNaN/Infinityconstants before any conversion, and the format name is validated before the JSON is parsed. The remaining options and error behavior matchfrom_data().
- 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 andDocument.to_data()produces for the selected format, so every exported document validates against it. It is a structural description, never full XSD validation: the rules JSON Schema cannot carry are listed underx-pyxsd-validation.unvalidated, andrequire_valid()remains the complete-validation gate.format- the data format contract;"pyxsd-json"is the schema-driven profile this method documents.element- an optional local, Clark, or EQName spelling that selects the described root;Nonedescribes every concrete global root withanyOf.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.
- class pyxsd.ValidationError(message, report)¶
Raised by
require_valid()when a report contains errors.report: theValidationReportwhose errors caused the raise; inspect it instead of parsing the message.
- Parameters:
message (str)
report (ValidationReport)
- class pyxsd.XMLNode(*args, **kwargs)¶
Structural type of one node in a parsed instance tree.
Both the generated schema classes and the synthetic nodes built by
Transform.makeElemObjsatisfy this protocol:_name_: the element’s tag name._attribs_: attribute names mapped to their lexical values._children_: child nodes in document order (a child may beNonewhen an optional element is absent)._value_: the element’s text split on line boundaries, orNonewhen it has none.
- class pyxsd.XPathError¶
The expression is outside the identity-constraint XPath subset.
- class pyxsd.XmlLimits(max_bytes=None, max_depth=None, max_elements=None)¶
Optional structural budgets for one XML parse.
Every bound is inclusive and counted on the input as supplied:
max_byteson file/binary-stream bytes or UTF-8 encoded bytes for text-mode streams,max_depthon element nesting (the root is depth 1), andmax_elementson start tags.Noneleaves that budget unset.
- class pyxsd.XmlParserPolicy(use_defusedxml=False, forbid_dtd=False, forbid_entities=False, forbid_external=False)¶
An immutable, opt-in XML parser posture.
The forbid flags are meaningful only with
use_defusedxml=True; constructing a policy that asks for declaration denial without the defusedxml parser would silently ignore the request, so it is rejected.- classmethod default()¶
Stdlib ElementTree with today’s DTD/entity behavior and no overhead.
- Return type:
- classmethod protected()¶
Defusedxml; forbid entity declarations and external references.
Plain DTD syntax stays allowed, so harmless internal
ATTLISTdefaults still apply.- Return type:
- classmethod strict()¶
Defusedxml; forbid DTDs, entity declarations, and external references.
- Return type:
- pyxsd.compile(source, *, mode=BindingPolicy(invalid_value='drop', unresolved_type='error', undeclared_content='error', whitespace='xsd', namespaces='strict', facets='strict'), xsd_version='1.1', namespace_schemas=None, overlay=None, namespace_context=None, schema_location_pairs=None, extensions=None, resource_policy=None, xml_policy=None, xml_limits=None, base_uri=None, _source_purpose='schema')¶
Schema.compile()exposed as a module-level function.- Parameters:
mode (Any)
xsd_version (Literal['1.0', '1.1'])
namespace_context (NamespaceContext | None)
extensions (Extensions | None)
resource_policy (ResourcePolicy | None)
xml_policy (XmlParserPolicy | None)
xml_limits (XmlLimits | None)
base_uri (str | None)
_source_purpose (Literal['schema', 'schema-hint', 'instance', 'text', 'collection'])
- Return type:
- pyxsd.parse(xml, *, xsd=None, mode=BindingPolicy(invalid_value='drop', unresolved_type='error', undeclared_content='error', whitespace='xsd', namespaces='strict', facets='strict'), namespace_schemas=None, overlay=None, resource_policy=None, xml_policy=None, xml_limits=None)¶
Parses xml against its schema and returns a
Document.The schema is the one named by
xsdwhen given; otherwise the instance’s ownxsi:schemaLocation/xsi:noNamespaceSchemaLocationhints name it, resolved relative to the instance document’s directory (the working directory for stream sources). An instance that names no schema raisesPyXSDError. A hint naming an absolute URI stays a URI and is never reinterpreted as a local path: a policy reads it under purpose"schema-hint"and, without a remote-capable policy, it raisesResourcePolicyError.xml- the instance document: a file path, a file object open for reading, or a parsedxml.etree.ElementTree.Elementused as the document root directly.xsd- the schema to bind against: a path or a file object open for reading. Defaults to the instance’s schema hints.mode,namespace_schemas,overlay- passed toSchema.compile().resource_policy- a trusted application resource policy for both the instance and schema documents. Itsparse()owns XML parsing, soxml_policy/xml_limitscannot be combined with it.xml_policy/xml_limits- opt-in parser posture and structural budgets applied explicitly to the instance and to the schema compile. They never become an implicit default for laterSchema.parse()calls.
- Parameters:
mode (Any)
resource_policy (ResourcePolicy | None)
xml_policy (XmlParserPolicy | None)
xml_limits (XmlLimits | None)
- Return type: