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" binds None (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 own str.strip does.

  • 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, length and the other length facets, minInclusive/maxInclusive and their exclusive pairs, totalDigits/fractionDigits, and whiteSpace) 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:
  • invalid_value (Literal['drop', 'raw'])

  • unresolved_type (Literal['error', 'generic'])

  • undeclared_content (Literal['error', 'generic'])

  • whitespace (Literal['xsd', 'compat'])

  • namespaces (Literal['legacy', 'strict'])

  • facets (Literal['strict', 'off'])

invalid_value: Literal['drop', 'raw'] = 'drop'
unresolved_type: Literal['error', 'generic'] = 'error'
undeclared_content: Literal['error', 'generic'] = 'error'
whitespace: Literal['xsd', 'compat'] = 'xsd'
namespaces: Literal['legacy', 'strict'] = 'strict'
facets: Literal['strict', 'off'] = 'strict'
replace(**changes)

Return a copy with the given fields changed.

BindingPolicy().replace(invalid_value="raw") is the supported way to tweak one field of a preset.

Parameters:

changes (object)

Return type:

BindingPolicy

class pyxsd.Document(schema, root, source, report, *, provenance=None, declarations=None, xdm_capture=None)

A schema-bound instance document: the interaction hub.

schema is None for a schemaless document. Schema-dependent operations such as revalidate() 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 None when the document is schemaless.

root: Any

The bound root instance, or None when 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:

NodeLookup

property report: ValidationReport

schema-phase issues, then instance-phase.

Type:

The merged report

property is_valid: bool

Whether the report holds no error-severity issues.

require_valid()

Raises pyxsd.ValidationError if the report has errors.

Return type:

None

write(dest)

Writes the bound tree to dest (a path or a file object).

Parameters:

dest (str | Path | PathLike[str] | IO[str])

Return type:

None

to_string()

Returns the bound tree serialized as XML text.

Return type:

str

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-parsed Element uses its ElementTree serialization. RELAX NG captures a pre-parsed Element structurally, 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 raises XdmInputError instead of returning a view that disagrees with the document.

Return type:

XdmDocument

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 in docs/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() and xpath() 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.

Parameters:
Return type:

dict

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 native to_dict() structure and converts its scalars to JSON-safe values. format="pyxsd-json" uses the compiled schema’s layout and the root-preserving Q{uri}local profile. typed and always_list are native-only options; another format rejects a non-default value with ValueError.

Parameters:
Return type:

JsonValue

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/NaN strings.

Parameters:
Return type:

str

transform(fn, *args, **kwargs)

Applies fn to the document.

A DocumentTransform is 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, including None, which is returned unchanged. The schema-specific node check is the narrow _document_for_node_result hook: XSD wraps a bound SchemaBase root, while RELAX NG wraps its lexical RelaxNGElement tree. When a transform mutates the tree in place and returns None, 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.

Parameters:
Return type:

Document | Any

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 source is carried over, and so is the original parse’s DTD declaration evidence: serialization drops the DOCTYPE, so rebinding with the recorded evidence keeps a declared ENTITY/ENTITIES value 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) raises PyXSDError because there is no schema to bind against. Use SchemalessDocument.revalidate() to refresh a schemaless document from its current lexical tree.

Return type:

Document

walk()

Yields every node of the bound tree, pre-order.

Return type:

Iterator[Any]

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, text mirrors _value_ and a child’s tail mirrors its recorded _tail_, so mixed character data is queryable in document order. Parsing does not preserve comment nodes, and an element with _value_ is None projects text=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. See docs/data-model.md.

Parameters:
Return type:

Any

find(path, *, namespaces=None)

Finds the first node matching an ElementTree path.

Unlike xpath(), this accepts ElementTree’s path subset ({uri}name qualified names, *, ., .., //). Returns the original bound node, or None. The projection contract documented on xpath() applies here too.

Parameters:
Return type:

Any

findall(path, *, namespaces=None)

Finds every node matching an ElementTree path.

Like find(), but returns a list of the original bound nodes (possibly empty). See xpath() for the projection contract.

Parameters:
Return type:

list[Any]

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)). Every for_* selector compiles to a predicate over the type ER immediately; for_path is 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"). Without mixin, returns a decorator that registers the decorated class.

Parameters:
Return type:

Any

for_namespace(uri, mixin=None)

Registers mixin for every type declared in namespace uri.

An empty or None uri selects declarations that have no namespace.

Parameters:
  • uri (str | None)

  • mixin (type | None)

Return type:

Any

for_kind(kind, *, derived_from=None, mixin=None)

Registers mixin for types of kind (simpleType or complexType).

With derived_from, only types whose superClassNames list the given base (matched by local or expanded spelling) qualify.

Parameters:
  • kind (str)

  • derived_from (str | None)

  • mixin (type | None)

Return type:

Any

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.

Parameters:
Return type:

Any

where(predicate, mixin=None)

Registers mixin for every type ER satisfying predicate.

Parameters:
Return type:

Any

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.

Parameters:
Return type:

tuple[type, …]

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 of read_timeout and the time left before request_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-Length is 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 expired request_seconds deadline. DNS, TLS, and socket failures (including a read timeout shorter than the remaining deadline) propagate as the original OSError subclass. Either way the connection is already closed when the exception escapes.

Parameters:

clock (Callable[[], float])

fetch(url, *, limits)
Parameters:
Return type:

RemoteResponse

class pyxsd.NamespaceError

A QName used a prefix that is not bound in its scope.

class pyxsd.ParseModes

Named BindingPolicy presets for Schema.compile.

Each attribute is an ordinary policy, so a caller can pass ParseModes.LAX for a convenient preset or a hand-built BindingPolicy for 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_bytes bounds one downloaded resource and closure_bytes bounds all resources fetched for one compilation. resources and depth bound the dependency closure, redirects bounds the hops the caller may authorize, and the three timeouts configure connecting, each socket read, and the total request. xml_depth and xml_elements are structural limits for the strict parser that consumes a downloaded resource.

Parameters:
  • response_bytes (int)

  • closure_bytes (int)

  • resources (int)

  • depth (int)

  • redirects (int)

  • connect_timeout (float)

  • read_timeout (float)

  • request_seconds (float)

  • xml_depth (int)

  • xml_elements (int)

response_bytes: int = 16777216
closure_bytes: int = 134217728
resources: int = 128
depth: int = 16
redirects: int = 5
connect_timeout: float = 10.0
read_timeout: float = 30.0
request_seconds: float = 30.0
xml_depth: int = 256
xml_elements: int = 250000
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 instance xsi:schemaLocation / xsi:noNamespaceSchemaLocation that names a remote schema needs allow_remote_hints=True as well. A local schema (or anonymous stream) may reference a remote dependency only with allow_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 exceeds limits.closure_bytes, limits.resources unique URLs, and limits.depth dependency levels. Redirects are followed one request at a time, with the scheme, origin, and addresses revalidated before each new request, up to limits.redirects hops. Every downloaded body counts toward closure_bytes, including redirect and error responses, and limits.redirects is 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 needs allow_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. Direct read calls 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).

parse always uses XmlParserPolicy.strict() and the policy’s XML limits (response_bytes for bytes, xml_depth and xml_elements for 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.

resolver is 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).

limits defaults to a fresh RemoteLimits; transport defaults to HttpClientTransport; resolver defaults to the system resolver.

Parameters:
limits: RemoteLimits
allowed_origins: frozenset[tuple[str, str, int]]
allow_remote_hints: bool
allow_local_remote: bool
allow_private_addresses: bool
compilation(*, root_read=True)

Isolate the closure state of one in-flight compilation.

root_read is 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.

Parameters:

root_read (bool)

Return type:

Iterator[None]

read(source, *, base, purpose)

Read a local resource or an authorized remote schema.

Parameters:
  • source (str)

  • base (str | None)

  • purpose (Literal['schema', 'schema-hint', 'instance', 'text', 'collection'])

Return type:

ResourceData

parse(data, context)

Parse admitted bytes with the strict defused profile and XML limits.

Parameters:
Return type:

Element

class pyxsd.RemoteResponse(url, status, headers, content)

One HTTP response, bounded and exactly as received.

headers keeps HTTP field-name case-insensitivity, so a redirect’s Location is found however the server cased it.

Parameters:
url: str
status: int
headers: Mapping[str, str]
content: bytes
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:
Return type:

RemoteResponse

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. purpose is a ResourcePurpose: "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 through xsi:schemaLocation or xsi: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:
  • source (str)

  • base (str | None)

  • purpose (Literal['schema', 'schema-hint', 'instance', 'text', 'collection'])

Return type:

ResourceData

parse(data, context)

Parse admitted bytes and record namespace evidence.

Parameters:
Return type:

Element

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 V that vc:* selectors were tested against; the schema’s own vocabulary is not restricted by it (that is the compiler’s job, see version_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).

components: Any

The component table registered during compilation.

namespace_context: Any

Prefix-to-URI bindings captured while parsing the schema documents.

mode: Any

The binding policy the compilation ran under.

target_namespace: str | None

The main schema document’s targetNamespace, if it declared one.

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-parsed xml.etree.ElementTree.Element used as the schema document root directly. An unopenable file, malformed XML, or a document whose root is not xs:schema raise PyXSDError; schema-legality problems are collected on report instead. A caller that supplies an Element also supplies its namespace evidence on namespace_context; no serialization or reparse occurs.

  • mode - a BindingPolicy (usually a ParseModes preset). Defaults to NAMESPACED.

  • xsd_version - the XSD processor version the document is compiled as, "1.0" or "1.1" (default "1.1"). It is the declared version vc:* conditional-inclusion selectors test against: in "1.0" mode a declaration carrying vc:minVersion="1.1" is dropped (XSD 1.1 §4.2.2). The vocabulary itself is checked separately (see pyxsd.version_gates).

  • namespace_schemas - an optional {namespace_uri: path} mapping supplying schemas for namespaces referenced by xs:import without a schemaLocation.

  • 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’s xsi:schemaLocation beyond the main schema. Advisory hints: consulted in strict namespace mode only, and one that cannot be loaded is a schema-hint warning (parse() passes the instance’s pairs; a schema-only compile has none).

  • extensions - an optional Extensions registry 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. Its parse() owns XML parsing, so xml_policy and xml_limits cannot be combined with it.

  • xml_policy - an opt-in XmlParserPolicy applied to the main schema and every included/imported dependency. None keeps stdlib parsing and its current DTD/entity behavior. The choice is compile- scoped: it never becomes the default for later parse() calls.

  • xml_limits - optional XmlLimits byte/depth/element budgets for the same documents.

  • base_uri - the base reference for an already-parsed Element (or a stream with no path), used to resolve relative xs:include/xs:import locations 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:
Return type:

Schema

require_valid()

Raises pyxsd.ValidationError if 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 Any with 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 .pyi source:

    schema.stub()              # full .pyi document
    schema.stub(compact=True)  # compact agent-oriented view
    

The CLI emits the same text: pyxsd --emit-stubs [PATH] -s SCHEMA writes the full document to PATH (stdout when PATH is omitted), and adding --stubs-compact selects the compact view.

component_ids optionally selects native declaration IDs, with depth bounding their outgoing dependencies (None follows all). Unknown IDs raise KeyError and negative depths raise ValueError. See pyxsd.introspection for 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.

Parameters:
Return type:

str

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:
Return type:

Iterator[ParseOutcome]

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 parsed xml.etree.ElementTree.Element used as the document root directly. An unopenable file or malformed XML raises PyXSDError (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 from compile(); None keeps stdlib parsing and unlimited structure. They cannot be combined with a custom resource_policy, whose parse() is trusted application code. A pre-parsed Element is 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-complete XdmDocument and 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 whose read() 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-parsed Element is 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 report merges this schema’s (frozen) compilation issues with the document’s own binding issues. Document.root is None when the document root matched no global element declaration (the unknown-root issue records why).

Parameters:
Return type:

Document

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) raise PyXSDError before 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 raises ValueError.

Parameters:
Return type:

Document

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-standard NaN/Infinity constants before any conversion, and the format name is validated before the JSON is parsed. The remaining options and error behavior match from_data().

Parameters:
Return type:

Document

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 Document.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 under x-pyxsd-validation.unvalidated, and require_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; None describes every concrete global root with anyOf.

  • 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 (Literal['pyxsd', 'pyxsd-json', 'parker', 'badgerfish', 'jsonml'])

  • element (str | None)

  • fidelity (Literal['strict', 'best-effort'])

  • typed (bool)

  • always_list (bool)

Return type:

dict[str, object]

class pyxsd.ValidationError(message, report)

Raised by require_valid() when a report contains errors.

  • report: the ValidationReport whose errors caused the raise; inspect it instead of parsing the message.

Parameters:
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.makeElemObj satisfy 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 be None when an optional element is absent).

  • _value_: the element’s text split on line boundaries, or None when 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_bytes on file/binary-stream bytes or UTF-8 encoded bytes for text-mode streams, max_depth on element nesting (the root is depth 1), and max_elements on start tags. None leaves that budget unset.

Parameters:
  • max_bytes (int | None)

  • max_depth (int | None)

  • max_elements (int | None)

max_bytes: int | None = None
max_depth: int | None = None
max_elements: int | None = None
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.

Parameters:
  • use_defusedxml (bool)

  • forbid_dtd (bool)

  • forbid_entities (bool)

  • forbid_external (bool)

use_defusedxml: bool = False
forbid_dtd: bool = False
forbid_entities: bool = False
forbid_external: bool = False
classmethod default()

Stdlib ElementTree with today’s DTD/entity behavior and no overhead.

Return type:

XmlParserPolicy

classmethod protected()

Defusedxml; forbid entity declarations and external references.

Plain DTD syntax stays allowed, so harmless internal ATTLIST defaults still apply.

Return type:

XmlParserPolicy

classmethod strict()

Defusedxml; forbid DTDs, entity declarations, and external references.

Return type:

XmlParserPolicy

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:
Return type:

Schema

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 xsd when given; otherwise the instance’s own xsi:schemaLocation / xsi:noNamespaceSchemaLocation hints name it, resolved relative to the instance document’s directory (the working directory for stream sources). An instance that names no schema raises PyXSDError. 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 raises ResourcePolicyError.

  • xml - the instance document: a file path, a file object open for reading, or a parsed xml.etree.ElementTree.Element used 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 to Schema.compile().

  • resource_policy - a trusted application resource policy for both the instance and schema documents. Its parse() owns XML parsing, so xml_policy/xml_limits cannot 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 later Schema.parse() calls.

Parameters:
Return type:

Document