Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ docs/superpowers/

# Docs build output
docs/_build/
docs/autoapi/

# Downloaded schemas for the docx and gpx examples
# (fetch on demand; too large to commit)
Expand Down
10 changes: 10 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Agent guidance for pyxsd

## Python API documentation

- Write public docstrings in Sphinx-compatible reStructuredText. Record
behavior, limits, and errors that signatures do not convey.
- Add new exports to `__all__` where the module uses it. AutoAPI picks up
public members of covered modules; add new supported import paths to
`PUBLIC_API_MODULES` in `docs/conf.py`.
- Check reference changes with
`uv run sphinx-build -E -n -W -b html docs docs/_build/html`.

## Example outputs carry no library markers

- Rendered artifacts (SVG, HTML, PDF, PNG, WAV, console output) must not
Expand Down
18 changes: 18 additions & 0 deletions docs/_templates/autoapi/python/package.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{% extends "python/module.rst" %}

{% block content %}
{{ super() }}
{% if obj.id == "pyxsd" %}
Public exports
--------------

{% for name, kind in lazy_exports if name not in obj.children|map(attribute="short_name")|list %}
.. auto{{ kind }}:: pyxsd.{{ name }}
{% if kind == "class" %}
:members:
:undoc-members:
{% endif %}

{% endfor %}
{% endif %}
{% endblock %}
8 changes: 8 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@
Use {doc}`quickstart` for a complete first example. This page documents public
entry points; {doc}`data-model` describes node storage and export behavior.

For generated signatures and docstrings by module, browse the
{doc}`Python API <autoapi/pyxsd/index>`.

```{contents} On this page
:local:
:depth: 1
```

## Schema and documents

`Schema.compile(source, ...)` generates binding classes once;
Expand Down
166 changes: 164 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@

from __future__ import annotations

import logging
import sys
from pathlib import Path

from sphinx.domains.python import PythonDomain
from sphinx.ext import viewcode
from sphinx.util.nodes import make_refnode

SRC = Path(__file__).resolve().parent.parent / "src"
if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))
Expand All @@ -13,10 +18,10 @@
copyright = "2026, the pyxsd contributors"
author = "the pyxsd contributors"

from pyxsd import __version__ # noqa: E402
import pyxsd # noqa: E402

#: Full version (MAJOR.MINOR.MICRO) shown in the docs header and search.
release = __version__
release = pyxsd.__version__
#: Short form (MAJOR.MINOR) Sphinx uses for the version banner.
version = ".".join(release.split(".")[:2])

Expand All @@ -26,6 +31,8 @@
"sphinx.ext.autosummary",
"sphinx.ext.napoleon",
"sphinx.ext.intersphinx",
# Load viewcode after AutoAPI so existing source links use Sphinx's analyzer.
"autoapi.extension",
"sphinx.ext.viewcode",
"sphinx_copybutton",
"sphinx_llms_txt",
Expand Down Expand Up @@ -95,6 +102,161 @@
autodoc_member_order = "bysource"
autodoc_typehints = "description"

# Scan implementation modules so AutoAPI can resolve facade re-exports.
# Publish only supported import paths, not the entire implementation tree.
autoapi_dirs = ["../src/pyxsd"]
autoapi_python_use_implicit_namespaces = True
autoapi_add_toctree_entry = False
autoapi_template_dir = "_templates/autoapi"
# These optional adapters are not needed to resolve the public facades.
autoapi_ignore = ["*/pyxsd/mcp/*", "*/pyxsd/relaxng/pydantic_adapter.py"]
autoapi_options = ["members", "undoc-members", "imported-members", "show-module-summary"]
PUBLIC_API_MODULES = frozenset(
{
"pyxsd",
"pyxsd.batch",
"pyxsd.integrations",
"pyxsd.introspection",
"pyxsd.relaxng",
"pyxsd.resource_policy",
"pyxsd.schemaless",
"pyxsd.stubs",
"pyxsd.transforms",
"pyxsd.validation",
"pyxsd.xdm",
"pyxsd.xpath",
"pyxsd.xslt",
}
)


def skip_api_member(app, what, name, obj, skip, options):
if what in {"module", "package"} and name not in PUBLIC_API_MODULES:
return True
return None


def is_generated_api(docname):
return docname.startswith("autoapi/")


class ReferencePythonDomain(PythonDomain):
"""Keep both pages' anchors, but prefer hand-authored cross-reference targets."""

def note_object(self, name, objtype, node_id, aliased=False, location=None):
generated = is_generated_api(self.env.current_document.docname)
if previous := self.objects.get(name):
was_generated = is_generated_api(previous.docname)
if generated and not was_generated:
return
if was_generated and not generated:
del self.objects[name]
# Autodoc's short annotation names would otherwise match both public
# paths for these classes, which the guide already documents by module.
if generated and name in {"pyxsd.XmlLimits", "pyxsd.XmlParserPolicy"}:
aliased = True
super().note_object(name, objtype, node_id, aliased, location)

def note_module(self, name, node_id, synopsis, platform, deprecated):
previous = self.modules.get(name)
if not (
is_generated_api(self.env.current_document.docname)
and previous
and not is_generated_api(previous.docname)
):
super().note_module(name, node_id, synopsis, platform, deprecated)


class StaticImportFilter(logging.Filter):
"""Ignore internal registry cycles regardless of which module is scanned first."""

def filter(self, record):
if getattr(record, "subtype", None) != "python_import_resolution":
return True
prefix = "Cannot resolve cyclic import: "
message = record.getMessage()
if not message.startswith(prefix):
return True
modules = message.removeprefix(prefix).split(", ")
# The final module repeats at the start of the cycle. Ignore only
# cycles involving the XSD registry, not unrelated import warnings.
cycle = modules[modules.index(modules[-1]) :]
return (
"pyxsd.element_representatives.element_representative" not in cycle
or not PUBLIC_API_MODULES.isdisjoint(cycle)
)


def prepare_api_templates(env):
# AutoAPI cannot see imports guarded by TYPE_CHECKING. Autodoc can
# resolve these exports directly through the package's lazy __getattr__.
env.globals["lazy_exports"] = [
(name, "class" if isinstance(getattr(pyxsd, name), type) else "function")
for name in pyxsd.__all__
if not name.startswith("_")
]


autoapi_prepare_jinja_env = prepare_api_templates


def resolve_generated_type(app, env, node, content):
"""Link implementation names to their public re-exports where possible."""
if node.get("refdomain") != "py":
return None

docname = node["refdoc"]
target = node["reftarget"]
domain = env.get_domain("py")
parent, _, member = target.rpartition(".")
for symbol in getattr(env, "autoapi_all_objects", {}).values():
origin = symbol.obj.get("original_path")
if origin and origin in (target, parent):
public_name = symbol.id if origin == target else f"{symbol.id}.{member}"
if entry := domain.objects.get(public_name):
return make_refnode(app.builder, docname, entry.docname, entry.node_id, content)

# AutoAPI signatures also describe types that have no public reference
# page. Keep inferred annotations readable; explicit roles stay checked.
if is_generated_api(docname) and (
"refexplicit" not in node or (node.get("reftype") == "class" and not node.get("refwarn"))
):
return content
return None


def isolate_api_annotations(app, docname, source):
# AutoAPI's type fields must not replace autodoc's on the existing pages.
if not is_generated_api(docname):
app.env.temp_data.pop("annotations", None)


def reference_viewcode(app, doctree):
# Viewcode builds backlinks using defining modules, not the public
# aliases used by AutoAPI. Keep source links on the existing pages.
if not is_generated_api(app.env.current_document.docname):
viewcode.doctree_read(app, doctree)


def finish_api_build(app, exception):
logging.getLogger("sphinx.autoapi._mapper").removeFilter(app._static_import_filter)


def setup(app):
app.add_domain(ReferencePythonDomain, override=True)
for listener in app.events.listeners["doctree-read"]:
if listener.handler is viewcode.doctree_read:
app.disconnect(listener.id)
app.connect("doctree-read", reference_viewcode, priority=listener.priority)
break
app.connect("autoapi-skip-member", skip_api_member)
app.connect("source-read", isolate_api_annotations, priority=600)
app.connect("missing-reference", resolve_generated_type)
app._static_import_filter = StaticImportFilter()
logging.getLogger("sphinx.autoapi._mapper").addFilter(app._static_import_filter)
app.connect("build-finished", finish_api_build)


# Strict cross-references: repair public targets in the docs, not broad ignores.
nitpicky = True
nitpick_ignore = [
Expand Down
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ skills
:caption: Reference and limits

api
Python API <autoapi/pyxsd/index>
cli
supported
xml-security
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ docs = [
"furo>=2025.7",
"sphinx-copybutton>=0.5.2",
"sphinx-llms-txt>=0.7.1",
"sphinx-autoapi>=3.9",
]
# Runnable consumer examples are examples-only environments; these are not
# published extras and must never be installed by library users implicitly.
Expand Down
2 changes: 1 addition & 1 deletion src/pyxsd/binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class ParseModes:
#: for callers that need the pre-namespaced behavior.
STRICT = BindingPolicy(namespaces="legacy")

#: Keep the report strict, but bind best-effort values: invalid
#: 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.
Expand Down
3 changes: 1 addition & 2 deletions src/pyxsd/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,8 +419,7 @@ def compile(
``xs:import`` without a ``schemaLocation``.

- ``overlay`` - an optional overlay class file, loaded after
class generation (experimental; see
:func:`load_overlay_classes`).
class generation (experimental).

- ``namespace_context`` - an existing prefix-to-URI binding
context for the schema documents' bindings to accumulate
Expand Down
4 changes: 2 additions & 2 deletions src/pyxsd/schemaless/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
def attribute(name: str, *, type: TypeRef | None = None) -> Any:
"""Declare one expanded-name attribute field.

Reads call :meth:`~pyxsd.schemaless.tree.SchemalessElement.attribute_value`
Reads call ``SchemalessElement.attribute_value``
and therefore follow the document's effective scalar policy; a missing
attribute reads as ``None``. Writes format the value through that same
adapter and replace only that attribute. *name* is an expanded (Clark)
Expand All @@ -51,7 +51,7 @@ def attribute(name: str, *, type: TypeRef | None = None) -> Any:
def text(*, type: TypeRef | None = None, default: Any = None) -> Any:
"""Declare the element's leading character data as a scalar field.

Reads call :meth:`~pyxsd.schemaless.tree.SchemalessElement.scalar_value`
Reads call ``SchemalessElement.scalar_value``
for present leading text and return *default* when there is none. Mixed
content stays mixed content: child tails are never concatenated into this
value. Writes replace only the leading text.
Expand Down
2 changes: 1 addition & 1 deletion src/pyxsd/stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
an error-bearing schema still compiles classes, and a stub may still be
requested for it.

On top of the inventory, :func:`_members` resolves one class's
On top of the inventory, ``_members`` resolves one class's
renderable members: its own element and attribute descriptors in
declaration order, members attributed from a base class the inventory
does not list (an overlay's generated base), and public functions and
Expand Down
2 changes: 1 addition & 1 deletion src/pyxsd/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class CompileContextProtocol(Protocol):
Annotation-only structural view of
:class:`~pyxsd.schema_composition.CompositionContext`, which
satisfies it without inheriting from it: the declaration and
derivation checks in :mod:`pyxsd.schema_checks` accept this
derivation checks in ``pyxsd.schema_checks`` accept this
protocol, so they depend on the attributes they actually touch
rather than on the concrete pipeline context.

Expand Down
2 changes: 1 addition & 1 deletion src/pyxsd/xdm/values.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class XdmItem:
"""Base class for one XDM item.

Concrete items are immutable. Nodes extend this class in
:mod:`pyxsd.xdm.nodes`; they are not value items and are never compared by
``pyxsd.xdm.nodes``; they are not value items and are never compared by
value here.
"""

Expand Down
2 changes: 1 addition & 1 deletion src/pyxsd/xslt/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""XSLT 3.0 compilation, invocation, and optional advisory inspection.

The normative processor, compiled stylesheet, and result views are the public
entry points. :mod:`pyxsd.xslt.inspection` remains a separate, non-normative
entry points. :func:`inspect_stylesheet` provides a separate, non-normative
binding of the packaged XSLT schemas; it never decides acceptance or compiles
the stylesheet.
"""
Expand Down
2 changes: 1 addition & 1 deletion src/pyxsd/xslt/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,7 @@ def as_transform(
complete transformation result; the callback only observes.

This method constructs the adapter only: conversion, validation,
and result handling live in :mod:`pyxsd.xslt.adapter`.
and result handling live in ``pyxsd.xslt.adapter``.
"""
from pyxsd.xslt.adapter import XsltDocumentTransform

Expand Down
Loading
Loading