Skip to content

Module Reference

Module Reference

Complete API reference for the pyrs_yaml module.

Version compatibility

pyrs-yaml ships as an ABI3 wheel, so a single wheel works across Python 3.8–3.15 — no recompilation needed when upgrading Python.

Core Functions

parse()

Parse a YAML string or bytes into a YamlDocument.

parse(yaml: str | bytes, resolve_merges: bool = True, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> YamlDocument

Parameters:

  • yaml — YAML content as str or bytes
  • resolve_merges — Whether to resolve merge keys (<<: *alias) after parsing (default: True)
  • schema — Schema name ("core", "json", "failsafe", "yaml1.1", or a registered custom name), or an inline schema dict (see YAML Schema Language)
  • max_depth — Maximum nesting depth (default: 1000)
  • allow_duplicate_keys — Whether to allow duplicate mapping keys (default: None, which reads as "as_is")
  • duplicate_keys — What the reader does when one mapping holds two keys that YAML counts as one (default: "as_is"). "as_is" answers each identity class as it always has: a scalar collision and a plain/quoted collision are refused, a second null or merge key folds onto the first slot, and a tag tells two keys apart under every value. "error" refuses the classes the default exempts too; "last_wins" folds silently to the later pair, which is what allow_duplicate_keys=True means; "first_wins" keeps the earlier pair's value and carries the folded pair's notes and anchor definitions onto the key that survives. Passing both this and allow_duplicate_keys is refused, not settled by precedence.
  • honor_version_directive — Version negotiation for an explicit %YAML directive (default: False). With True, a document declaring %YAML 1.1 is resolved under the YAML 1.1 profile and re-emits the directive; an explicit schema still wins.

Returns: A YamlDocument containing the parsed YAML

Raises:

  • YamlParseError — Invalid YAML syntax
  • YamlTypeError — Schema not found
  • TypeError — Input is not str or bytes

Example:

doc = pyrs_yaml.parse("key: value")
doc = pyrs_yaml.parse(b"key: value")
doc = pyrs_yaml.parse(yaml_str, schema="json")
doc = pyrs_yaml.parse(
    "addr: 0xFF", schema={"extends": "core", "rules": [{"pattern": "^0x[0-9a-fA-F]+$", "type": "int"}]}
)

parse_file()

Parse a YAML file.

parse_file(path: str, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> YamlDocument

Parameters:

Returns: A YamlDocument

Raises:

  • IOError — File not found or unreadable
  • YamlParseError — Invalid YAML
  • YamlTypeError — Schema not found

Example:

doc = pyrs_yaml.parse_file("config.yaml")

parse_all_docs()

Parse multiple YAML documents from a string.

parse_all_docs(yaml: str, resolve_merges: bool = True, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> list[YamlDocument]

Parameters:

  • yaml — YAML content with one or more documents (--- separated)
  • schema — Schema name or inline dict (see YAML Schema Language)

Returns: A list of YamlDocument objects

Example:

docs = pyrs_yaml.parse_all_docs("a: 1\n---\nb: 2")

PyYAML-Compatible Functions

safe_load()

Parse a YAML string into a Python dict or list. Uses PyYAML-compatible API.

safe_load(yaml: str, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> dict[Any, Any] | list[Any]

Parameters:

Raises: YamlParseError, YamlTypeError

Example:

d = pyrs_yaml.safe_load("key: value")
d = pyrs_yaml.safe_load(
    "addr: 0xFF", schema={"extends": "core", "rules": [{"pattern": "^0x[0-9a-fA-F]+$", "type": "int"}]}
)

safe_loads()

Parse multiple YAML documents from a string into Python dicts/lists.

safe_loads(yaml: str, schema: str | dict = "core", max_depth: int = 1000, allow_duplicate_keys: bool | None = None, honor_version_directive: bool = False, duplicate_keys: str | None = None) -> list[dict[Any, Any] | list[Any]]

Parameters:

  • yaml — YAML content with one or more documents
  • schema — Schema name or inline dict (see YAML Schema Language)

Equivalent to: yaml.safe_loads() in PyYAML

safe_dump()

Serialize a Python object to YAML.

safe_dump(data: dict[str, Any] | list[Any] | ndarray) -> str

Equivalent to: yaml.safe_dump() in PyYAML

Supported input types: dict, list, str, int, float, bool, None, and numpy.ndarray (all dimensions and numeric dtypes: int8/16/32/64, uint8/16/32/64, float32/64, complex64/128, bool)

Alias: safe_dumps() — identical to safe_dump().

:material-json: Conversion Functions

from_dict()

Convert a Python dict to YAML string. Also accepts numpy.ndarray as a value inside the dict.

from_dict(data: dict[str, Any]) -> str

from_json()

Convert a JSON string to YAML string.

from_json(json_str: str) -> str

dump_file()

Serialize a Python object to YAML and write to file. Accepts dict, list, or numpy.ndarray.

dump_file(data: Any, path: str) -> None

Pydantic Integration

dump_pydantic()

Serialize a Pydantic model to a YAML string.

dump_pydantic(model: BaseModel) -> str

Uses model_dump(mode='json') to preserve string types (e.g. a "10001" zip code stays a string) before delegating to safe_dump.

Raises:

  • ImportError — pydantic is not installed
  • TypeError — model is not a Pydantic BaseModel instance

Example:

from pydantic import BaseModel
import pyrs_yaml


class User(BaseModel):
    name: str
    age: int


yaml_str = pyrs_yaml.dump_pydantic(User(name="Alice", age=30))

parse_as()

Parse a YAML string and validate it against a Pydantic model.

parse_as(model: type[BaseModel], src: str, **yaml_kwargs: Any) -> BaseModel

Parameters:

  • model — A Pydantic BaseModel subclass
  • src — YAML string to parse
  • **yaml_kwargs — Keyword arguments forwarded to the YAML() constructor

Returns: An instance of model validating the parsed YAML.

Raises:

  • ImportError — pydantic is not installed
  • TypeError — model is not a Pydantic BaseModel subclass
  • pydantic.ValidationError — the parsed data fails model validation

Example:

user = pyrs_yaml.parse_as(User, "name: Alice\nage: 30")
print(user.name)  # Alice

PyrsYamlConfigSettingsSource

A pydantic-settings YAML source backed by pyrs-yaml. Drop-in replacement for pydantic_settings.YamlConfigSettingsSource that uses pyrs-yaml as the parser instead of PyYAML.

PyrsYamlConfigSettingsSource(
    settings_cls: type[BaseSettings],
    yaml_file: ConfigFileSourceType | None = DEFAULT_PATH,
    yaml_file_encoding: str | None = None,
    yaml_config_section: str | None = None,
    deep_merge: bool = False,
)

Loads settings from YAML file(s) declared via SettingsConfigDict(yaml_file=...) (or passed directly), then reads them with pyrs-yaml's parser under the YAML 1.2 core schema. All other pydantic-settings features — env-var and dotenv overlay, yaml_config_section (dot-notation paths included), deep_merge across multiple files, yaml_file_encoding — behave identically to YamlConfigSettingsSource.

Raises:

  • ImportError — pydantic-settings is not installed (install pyrs-yaml[settings])

Example:

from pydantic_settings import BaseSettings, SettingsConfigDict
import pyrs_yaml


class Settings(BaseSettings):
    app_name: str

    model_config = SettingsConfigDict(yaml_file="config.yaml")

    @classmethod
    def settings_customise_sources(
        cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings
    ):
        return (
            init_settings,
            env_settings,
            dotenv_settings,
            file_secret_settings,
            pyrs_yaml.PyrsYamlConfigSettingsSource(settings_cls),
        )

Note: the class is exported lazily — import pyrs_yaml never requires pydantic-settings. Accessing pyrs_yaml.PyrsYamlConfigSettingsSource without pydantic-settings installed raises ImportError with installation hints.

Tag Registry

register_tag()

Register a custom tag handler. Supports both decorator and imperative forms.

register_tag(name: str, handler: Callable | None = None, priority: int = 0) -> Callable

Example:

@pyrs_yaml.register_tag("!custom")
def handler(node):
    return f"custom:{node}"
pyrs_yaml.register_tag("!custom", handler_fn, priority=1)

remove_tag()

Remove a tag handler.

remove_tag(name: str) -> None

clear_tag_handlers()

Remove all registered tag handlers.

clear_tag_handlers() -> None

YAML Schema Language

register_schema()

Register a custom YAML schema from a schema definition string.

register_schema(name: str, schema_yaml: str) -> None

Parameters:

  • name — Schema name, used as YAML(schema=name)
  • schema_yaml — Schema definition in YAML format

The schema definition supports a rules list mapping regex patterns to YAML types, and an optional extends base schema:

pyrs_yaml.register_schema(
    "myapp",
    """
name: myapp
extends: core
rules:
  - pattern: ^0x[0-9a-fA-F]+$
    type: int
  - pattern: ^\\d{4}-\\d{2}-\\d{2}$
    type: str
""",
)

doc = pyrs_yaml.parse("addr: 0xFF", schema="myapp")
assert doc.get("addr") == 255

Raises: YamlParseError — Invalid schema definition

Schema as inline dict

The schema parameter of YAML(), parse(), parse_file(), parse_all_docs(), safe_load(), and safe_loads() also accepts an inline dict, which is serialized and registered automatically:

doc = pyrs_yaml.safe_load(
    "addr: 0xFF",
    schema={
        "extends": "core",
        "rules": [{"pattern": "^0x[0-9a-fA-F]+$", "type": "int"}],
    },
)
assert doc["addr"] == 255

Community Plugins

CustomType

Base class for custom YAML node types. Subclass it to define a type that can be used with YAML tags.

class CustomType:
    python_type = None  # set to a Python type for isinstance checks

    def can_parse(self, node) -> bool: ...
    def from_yaml(self, value: str): ...
    def to_yaml(self, obj) -> str: ...
    def validate(self, obj) -> bool: ...

Methods:

  • python_type — Optional Python type used during serialization (isinstance)
  • can_parse(node) — Whether this type handles a given node
  • from_yaml(value) — Convert a YAML string to a Python object (load)
  • to_yaml(obj) — Convert a Python object to a YAML string (dump)
  • validate(obj) — Validate a Python object's type and value

Built-in plugins include !!timestamp (datetime and datetime.date — the text decides which), !time (datetime.time), !uuid (uuid.UUID), !decimal (decimal.Decimal), !!binary (bytes, base64-encoded; the local !binary is still read), !regex (re.Pattern), and !set. The local !timestamp and !date tags are still read, so documents written by earlier versions keep their types; dumps use the standard tag because a local tag has no constructor in any other reader.

register_type()

Register a CustomType instance or class.

register_type(name: str, handler: CustomType | None = None) -> CustomType

Imperative form:

class TimestampType(pyrs_yaml.CustomType):
    python_type = datetime

    def from_yaml(self, value):
        return datetime.fromisoformat(value)

    def to_yaml(self, obj):
        return obj.isoformat()


pyrs_yaml.register_type("!timestamp", TimestampType())

Decorator form:

@pyrs_yaml.register_type("!timestamp")
class TimestampType(pyrs_yaml.CustomType): ...


doc = pyrs_yaml.parse("when: !timestamp 2026-08-11T10:30:00")
assert isinstance(doc.get("when"), datetime)

remove_type()

remove_type(name: str) -> None

Remove a registered custom type handler.

clear_type_handlers()

clear_type_handlers() -> None

Remove all registered custom type handlers.

Compliance

compliance_report()

Compute the YAML Test Suite compliance report.

compliance_report() -> dict

Returns the YAML Test Suite pass rate and per-test results.

Streaming Events

parse_stream()

Parse a document incrementally, yielding raw event dicts.

parse_stream(
    yaml: str | bytes, on_event=None, max_depth=1000, *, format="yaml"
) -> StreamIterator | None

Returns a StreamIterator yielding one event dict per step. Unlike YAML().load_stream() (which resolves into Python values), this exposes the raw token stream.

format picks the producer — yaml (the default), json, jsonc, json5 or toml — and every producer reports the one vocabulary, so the dicts keep the same nine keys (type, value, style, anchor, tag, line, column, offset, end). offset and end are the source-byte range of the event's own token — source.encode()[event["offset"]:event["end"]] decodes it — and where a producer records only a position, as every TOML event does, end equals offset. A comment event carries a tenth key, owner, naming which slot of which node the note is filed under. A field a format has nothing to say about stays None: anchor is YAML's own and alias never appears elsewhere, and a TOML literal '…' reads the same as a basic "…" because which quote was typed is not kept. A JSON or TOML stream carries one document, and the accept-or-refuse verdict is the one the tree route gives, because it is the same scanner. See Streaming Events for the per-key table.

YamlStream

The YamlStream class is a lazy event iterator returned by YAML().load_stream() and YAML().load_stream_file(). It yields parsed event dicts one at a time without loading the entire document into memory.

stream = yaml.load_stream_file("large.yaml")
for event in stream:
    print(event)

See YamlStream for full API details.

Async Functions

Async I/O wrappers via asyncio.run_in_executor. Non-blocking in event loop context.

safe_dump_async()

Serialize a Python object to a YAML string (async). Alias: safe_dumps_async().

async def safe_dump_async(data: Any) -> str

safe_loads_async()

Parse a YAML string into native Python objects (async).

async def safe_loads_async(yaml: str, schema: str = "core") -> Any

safe_load_async()

Parse a YAML string into native Python objects (async).

async def safe_load_async(yaml: str, schema: str = "core") -> Any

Example:

import asyncio, pyrs_yaml


async def main():
    yaml = await pyrs_yaml.safe_dumps_async({"a": 1})
    data = await pyrs_yaml.safe_loads_async(yaml)
    print(data)  # {'a': 1}


asyncio.run(main())

Markdown Frontmatter

read_markdown()

Extract YAML frontmatter from a Markdown file.

read_markdown(path: str, schema: str | dict = "core", max_depth: int = 1000) -> tuple[dict[Any, Any] | None, str]

Returns: (frontmatter_dict, content_string). If no frontmatter, frontmatter is None.

read_markdown_str()

Extract YAML frontmatter from a Markdown string.

read_markdown_str(content: str, schema: str | dict = "core", max_depth: int = 1000) -> tuple[dict[Any, Any] | None, str]

i18n Functions

set_language()

Set the language for error messages.

set_language(lang: str) -> None

Supported: "en", "zh-CN", "ja-JP", "ko-KR"

get_language()

Get the current language.

get_language() -> str

list_languages()

List all supported languages.

list_languages() -> list[str]

detect_language()

Auto-detect user's preferred language from environment variables.

detect_language() -> str

negotiate_language()

BCP 47 language negotiation.

negotiate_language(user_locales: list[str], default: str = "en") -> str

Exceptions

  • YamlParseError — YAML parsing error (inherits from ValueError)
  • YamlSerializeError — YAML serialization error (inherits from ValueError)
  • YamlTypeError — Type conversion error (inherits from TypeError)
  • YamlValidateError — JSON Schema validation error (inherits from ValueError)
  • YamlEditError — In-place edit failure (inherits from ValueError)
  • YamlPathError — Malformed/non-editable path (inherits from ValueError)
  • YamlDocumentError — Stale Node access (inherits from Exception)
  • YamlDuplicateKeyError — Duplicate mapping key detected (inherits from ValueError)
  • YamlMaxDepthError — Exceeded maximum nesting depth (inherits from ValueError)
  • YamlTagError — Invalid tag handler registration (inherits from ValueError)
  • YamlTagSkip — Sentinel raised by a tag handler to pass a node down the handler chain (inherits from YamlTagError)

Document.validate() answers inside this family throughout. It delegates the rules to jsonschema, which nothing here installs — the package depends on typing-extensions alone and its extras are cli, pydantic and settings — so run pip install jsonschema first. With no evaluator importable the call raises YamlValidateError whose message names that install route and carries the import error, even for a document the schema would pass. A schema given as text is this package's own door: it is read with json.loads before evaluation, and a text that is not JSON is refused with YamlValidateError (schema text must be JSON (…); pass the schema as a dict if it is not JSON), so the YAML spelling stays inside the family too. The evaluator not shipping with the library is a known boundary, documented for users in Quick Start and Custom Schemas.

See Exceptions for full details.

Version

__version__ = "0.19.1"

Generated API reference

Rendered by mkdocstrings from the library's own docstrings and generated type stub, so the signatures below come out of the code rather than being retyped.

pyrs_yaml

pyrs-yaml: High-performance Python library for YAML, TOML, JSON, JSONC and JSON5 with perfect round-trip support, built with Rust and PyO3.

This module provides Rust-backed parsers and serializers for all five formats, preserving comments, anchors, tags, and source formatting across round-trip conversions.

Example

import pyrs_yaml doc = pyrs_yaml.parse("key: value") print(doc.to_yaml()) key: value print(doc.get("key")) value

CustomType

Base class for custom YAML node types.

Subclass this to define a custom type that can be used with YAML tags:

class TimestampType(CustomType):
    python_type = datetime  # optional: for serialization isinstance check

    def from_yaml(self, value):
        return datetime.fromisoformat(value)

    def to_yaml(self, obj):
        return obj.isoformat()

    def can_parse(self, node):
        return True

register_type("!timestamp", TimestampType())
can_parse
can_parse(value)

Return True if this type should handle the given value.

value is the schema-resolved Python value (str, int, dict, list, etc.). Defaults to True: the tag match alone is sufficient. Override to gate handling on value content (e.g. value prefix).

Source code in python/pyrs_yaml/_type_registry.py
35
36
37
38
39
40
41
42
def can_parse(self, value: Any) -> bool:
    """Return True if this type should handle the given value.

    ``value`` is the schema-resolved Python value (str, int, dict, list,
    etc.). Defaults to True: the tag match alone is sufficient. Override
    to gate handling on value content (e.g. value prefix).
    """
    return True
from_yaml
from_yaml(value)

Convert a schema-resolved Python value to the target Python object.

value is the already-resolved Python value (str, int, dict, list, None, etc.). For scalar tags this is a str; for structured tags (e.g. !set) it can be a dict or list.

Source code in python/pyrs_yaml/_type_registry.py
44
45
46
47
48
49
50
51
def from_yaml(self, value: Any) -> Any:
    """Convert a schema-resolved Python value to the target Python object.

    ``value`` is the already-resolved Python value (str, int, dict, list,
    None, etc.). For scalar tags this is a str; for structured tags
    (e.g. ``!set``) it can be a dict or list.
    """
    return value
to_yaml
to_yaml(obj)

Convert a Python object to a YAML string value.

Source code in python/pyrs_yaml/_type_registry.py
53
54
55
def to_yaml(self, obj: Any) -> str:
    """Convert a Python object to a YAML string value."""
    return str(obj)
validate
validate(obj)

Validate a Python object's type and value.

Source code in python/pyrs_yaml/_type_registry.py
57
58
59
def validate(self, obj: Any) -> bool:
    """Validate a Python object's type and value."""
    return True

JsonLines

Iterator over the values of a line-delimited JSON stream, one document per line.

__iter__
__iter__()

Return self (iterator protocol).

__next__
__next__()

Yield the next line's value; None once the stream is exhausted.

A line the stream refuses raises with its position in the whole input, and the cursor does not move: asking again reports the same record rather than the one after it, because a record this format defines is not one to lose silently.

YamlStream

Lazy, constant-memory stream of YAML documents from a [ChunkCharIter].

__next__ parses exactly one event per call (driving the granit parser incrementally), so a large file is never fully buffered. Errors surface exactly once as a YamlParseError; after an error or close() the iterator returns None (StopIteration).

close
close()

提前终止:停止读取后续 chunk。幂等。

parse

parse(
    yaml,
    resolve_merges=True,
    schema=None,
    max_depth=1000,
    allow_duplicate_keys=None,
    honor_version_directive=False,
    duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def parse(
    yaml: str | bytes,
    resolve_merges: bool = True,
    schema: str | _SchemaDict | None = None,
    max_depth: int = 1000,
    allow_duplicate_keys: bool | None = None,
    honor_version_directive: bool = False,
    duplicate_keys: str | None = None,
) -> YamlDocument:
    return _parse(
        yaml,
        resolve_merges,
        _coerce_schema(schema),
        max_depth,
        allow_duplicate_keys,
        honor_version_directive,
        duplicate_keys,
    )

parse_file

parse_file(
    path,
    schema=None,
    max_depth=1000,
    allow_duplicate_keys=None,
    honor_version_directive=False,
    duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def parse_file(
    path: str,
    schema: str | _SchemaDict | None = None,
    max_depth: int = 1000,
    allow_duplicate_keys: bool | None = None,
    honor_version_directive: bool = False,
    duplicate_keys: str | None = None,
) -> YamlDocument:
    return _parse_file(
        path,
        _coerce_schema(schema),
        max_depth,
        allow_duplicate_keys,
        honor_version_directive,
        duplicate_keys,
    )

parse_all_docs

parse_all_docs(
    yaml,
    resolve_merges=True,
    schema=None,
    max_depth=1000,
    allow_duplicate_keys=None,
    honor_version_directive=False,
    duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
def parse_all_docs(
    yaml: str,
    resolve_merges: bool = True,
    schema: str | _SchemaDict | None = None,
    max_depth: int = 1000,
    allow_duplicate_keys: bool | None = None,
    honor_version_directive: bool = False,
    duplicate_keys: str | None = None,
) -> list[YamlDocument]:
    return _parse_all_docs(
        yaml,
        resolve_merges,
        _coerce_schema(schema),
        max_depth,
        allow_duplicate_keys,
        honor_version_directive,
        duplicate_keys,
    )

parse_stream builtin

parse_stream(
    yaml, on_event=None, max_depth=1000, *, format="yaml"
)

Event-stream parsing. With on_event callback, consumes events and returns None. Otherwise returns a lazy StreamIterator.

format chooses the producer: yaml (the default), json, jsonc, json5 or toml. Every producer reports the one vocabulary, so the dicts keep the same keys and only the fields a format has something to say about change. style is whatever that engine remembers: a JSON string reads double_quoted and a JSON number plain, JSON5 adds single_quoted, and a TOML literal '…' reads the same as a basic "…" because which quote was typed is not in its IR. anchor and alias stay YAML's own and never appear elsewhere. A comment event carries two keys about the note: style says whether the source gave the note a line of its own, and owner says which node the note is filed under and in which of its two slots — the node the consumer builds next (following_leading, following_inline) or the one it built last (preceding_leading, preceding_inline). max_depth bounds the YAML and JSON readers, which carry that knob; TOML's nesting limit is the intermediate representation's own. The accept/reject verdict is the same one the tree route reaches with the same detail, because it is the same scanner: a document load_json refuses raises here too.

With on_event the events arrive as they are produced and returning False stops the producer, not merely the delivery loop. What can stop is the format's own fact: json/jsonc/json5 stop scanning before the bytes of the next event, so a syntax error past that point is never reached; toml stops emitting from the intermediate representation its scan already built, so a refused document still raises — before any event is delivered. YAML's text producer is a push adapter over a scanner that cannot be aborted, so there False stops delivery after the whole document was parsed; load_stream is YAML's incremental surface. Without on_event the iterator materialises the document first.

safe_load

safe_load(
    yaml,
    schema=None,
    max_depth=1000,
    allow_duplicate_keys=None,
    honor_version_directive=False,
    duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def safe_load(
    yaml: str,
    schema: str | _SchemaDict | None = None,
    max_depth: int = 1000,
    allow_duplicate_keys: bool | None = None,
    honor_version_directive: bool = False,
    duplicate_keys: str | None = None,
) -> dict[Any, Any] | list[Any]:
    return _safe_load(
        yaml,
        _coerce_schema(schema),
        max_depth,
        allow_duplicate_keys,
        honor_version_directive,
        duplicate_keys,
    )

safe_loads

safe_loads(
    yaml,
    schema=None,
    max_depth=1000,
    allow_duplicate_keys=None,
    honor_version_directive=False,
    duplicate_keys=None,
)
Source code in python/pyrs_yaml/__init__.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def safe_loads(
    yaml: str,
    schema: str | _SchemaDict | None = None,
    max_depth: int = 1000,
    allow_duplicate_keys: bool | None = None,
    honor_version_directive: bool = False,
    duplicate_keys: str | None = None,
) -> list[dict[Any, Any] | list[Any]]:
    return _safe_loads(
        yaml,
        _coerce_schema(schema),
        max_depth,
        allow_duplicate_keys,
        honor_version_directive,
        duplicate_keys,
    )

safe_dump builtin

safe_dump(data)

Serialize a Python dict/list to a YAML string.

A tuple is read as a sequence, which is the shape the loader hands back for a YAML sequence key: safe_dump(safe_load(text)) has to accept what safe_load produced.

dump_file builtin

dump_file(data, path)

Serialize a Python object to YAML and write to a file.

from_dict builtin

from_dict(data)

Convert a Python dict/list to a YAML string (auto-selects block/flow style).

A tuple is read as a sequence; see [safe_dump].

from_json builtin

from_json(json_str)

Convert a JSON string to a YAML string.

from_jsonc builtin

from_jsonc(json_str)

Convert a JSONC string (JSON with // and /* ... */ comments) to a YAML string. Comments are NOT discarded on this projection: since

112/#115 they ride the AST's comment / leading_comment slots (so

to_jsonc can reproduce them), and the YAML writer renders those slots as # notes, which keeps the conversion lossless. Strictly a //-to-# change of syntax, not a change of language: everything else matches from_json semantics exactly.

from_json5 builtin

from_json5(json_str)

Convert a JSON5 string to a YAML string. JSON5 supersedes JSONC with trailing commas, single-quoted strings, unquoted identifier keys and the 0x… / .5 / Infinity / NaN numeric forms; like from_jsonc, comments survive the projection as YAML notes rather than being dropped.

from_toml builtin

from_toml(toml_str)

Convert a TOML string to a YAML string (hub-and-spoke exchange). TOML strings keep quoting so values never re-resolve; datetimes gain the !timestamp tag consumed by the built-in plugin.

load_json builtin

load_json(json_str)

Parse a strict JSON document directly into Python values (dict / list / scalar), mirroring the load_jsonc / load_json5 / load_toml family. Unlike load_jsonc this REJECTS the JSONC/JSON5 extensions — // and /* … */ comments, trailing commas, single-quoted strings, bare Infinity/NaN and 0x… forms all raise a parse error, exactly like json.loads / orjson.loads. Canonical strict JSON takes the same AST-free fast path load_jsonc uses (bytes → PyList/PyDict/scalars); any non-canonical shape (floats with exotic spellings, \u escapes, out-of-range ints) falls back to the strict AST parser that produces the identical value or the proper json-parse-error.

load_jsonc builtin

load_jsonc(json_str)

Parse a JSONC document directly into Python values (dict / list / scalar). Handy for TypeScript tsconfig.json, VS Code settings.json, and similar dialects without a pre-processing step.

load_json5 builtin

load_json5(json_str)

Parse a JSON5 document directly into Python values (dict / list / scalar). Accepts the full JSON5 grammar without a pre-processing step, mirroring load_jsonc on the wider dialect. Canonical strict JSON takes the same AST-free fast path load_json and load_jsonc use; every JSON5-only form falls through to the AST parser that owns the dialect's number and string semantics.

load_json_lines builtin

load_json_lines(json_str)

Iterate the values of a line-delimited JSON stream (NDJSON, JSON Lines, .jsonl): one complete document per line, resolved as the iterator is asked for rather than all up front.

Each value is what load_json returns for that line, and the stream keeps the engine's contract: a blank line, a line holding only a note, or a value that needs the next line to finish raises with its position in the whole input, and the refusal is reported again until the iteration stops.

load_toml builtin

load_toml(toml_str)

Parse TOML directly into a Python dict (values, not a document). Anchors cannot occur in TOML, so no alias resolution pass is needed.

load_ini

load_ini(text)

Parse INI text into a {section: {key: value}} dict.

Values are returned as raw strings (typed interpretation is left to the caller). Anonymous leading key = value lines land under the DEFAULT section and are inlined into every section, matching configparser semantics.

Source code in python/pyrs_yaml/ini.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def load_ini(text: str) -> dict[str, dict[str, str]]:
    """Parse INI text into a ``{section: {key: value}}`` dict.

    Values are returned as raw strings (typed interpretation is left to
    the caller). Anonymous leading ``key = value`` lines land under the
    DEFAULT section and are inlined into every section, matching
    configparser semantics.
    """
    parser = _CaseSensitiveParser(strict=True, inline_comment_prefixes=None)
    try:
        parser.read_string(text)
    except configparser.Error as e:
        # configparser raises its own hierarchy; the library's load-error
        # contract is ValueError-based (YamlParseError et al).
        raise ValueError(f"INI parse error: {e}") from e
    result: dict[str, dict[str, str]] = {}
    for section in parser.sections():
        result[section] = dict(parser.items(section))
    default = dict(parser.defaults())
    if default:
        result["DEFAULT"] = default
    return result

to_toml builtin

to_toml(yaml, schema='core')

Render a YAML document as TOML text. Rejects shapes TOML cannot hold (non-table root, null values, aliases, non-scalar keys) with stable toml-serialize-error messages.

read_markdown

read_markdown(path, schema='core', max_depth=1000)

Read a Markdown file and extract its YAML front matter, returning (frontmatter, body).

The argument is a path, not the text: read_markdown_str is the variant that takes content. The parameter was named content here while the native function it forwards to reads the file at that value, so the keyword path= - the only one that describes what the argument is - raised TypeError, and introspection reported a signature the runtime did not honour.

Source code in python/pyrs_yaml/__init__.py
356
357
358
359
360
361
362
363
364
365
366
367
368
def read_markdown(
    path: str,
    schema: str | _SchemaDict = "core",
    max_depth: int = 1000,
) -> tuple[dict[Any, Any] | None, str]:
    """Read a Markdown file and extract its YAML front matter, returning `(frontmatter, body)`.

    The argument is a path, not the text: `read_markdown_str` is the variant that takes content. The parameter was
    named `content` here while the native function it forwards to reads the file at that value, so the keyword
    `path=` - the only one that describes what the argument is - raised `TypeError`, and introspection reported a
    signature the runtime did not honour.
    """
    return _read_markdown(path, _coerce_schema(schema), max_depth)

read_markdown_str

read_markdown_str(content, schema='core', max_depth=1000)

Extract YAML front matter from a Markdown string, returning (frontmatter, body).

Source code in python/pyrs_yaml/__init__.py
371
372
373
374
375
376
377
def read_markdown_str(
    content: str,
    schema: str | _SchemaDict = "core",
    max_depth: int = 1000,
) -> tuple[dict[Any, Any] | None, str]:
    """Extract YAML front matter from a Markdown string, returning `(frontmatter, body)`."""
    return _read_markdown_str(content, _coerce_schema(schema), max_depth)

register_tag

register_tag(
    name: str, handler: _F, priority: int = 0
) -> _F
register_tag(
    name: str, handler: None = None, priority: int = 0
) -> Callable[[_F], _F]
register_tag(name, handler=None, priority=0)

Register a tag handler.

Supports both decorator and imperative forms

@register_tag("!custom") def handler(node): ...

@register_tag("!custom", priority=1) def handler(node): ...

register_tag("!custom", handler_fn) register_tag("!custom", handler_fn, priority=1)

Source code in python/pyrs_yaml/__init__.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def register_tag(name, handler=None, priority=0):
    """Register a tag handler.

    Supports both decorator and imperative forms:
        @register_tag("!custom")
        def handler(node):
            ...

        @register_tag("!custom", priority=1)
        def handler(node):
            ...

        register_tag("!custom", handler_fn)
        register_tag("!custom", handler_fn, priority=1)
    """
    if handler is not None:
        _rust_register_tag(name, handler, priority)
        return handler

    # Decorator form
    def decorator(fn):
        _rust_register_tag(name, fn, priority)
        return fn

    return decorator

remove_tag builtin

remove_tag(name)

Remove a specific tag handler.

clear_tag_handlers builtin

clear_tag_handlers()

Clear all tag handlers.

register_type

register_type(name: str, handler: _T) -> _T
register_type(
    name: str, handler: None = None
) -> Callable[[type[_T] | _T], type[_T] | _T]
register_type(name, handler=None)

Register a CustomType handler.

Supports both imperative and decorator forms:

register_type("!timestamp", TimestampType())

@register_type("!timestamp")
class TimestampType(CustomType):
    def from_yaml(self, value):
        return datetime.fromisoformat(value)

Parameters:

Name Type Description Default
name

The tag name (e.g. "!timestamp").

required
handler

A CustomType instance, or None for decorator form.

None
Source code in python/pyrs_yaml/_type_registry.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def register_type(name, handler=None):
    """Register a CustomType handler.

    Supports both imperative and decorator forms:

        register_type("!timestamp", TimestampType())

        @register_type("!timestamp")
        class TimestampType(CustomType):
            def from_yaml(self, value):
                return datetime.fromisoformat(value)

    Args:
        name: The tag name (e.g. "!timestamp").
        handler: A CustomType instance, or None for decorator form.
    """
    if handler is not None:
        _rust_register_type(name, handler)
        return handler

    # Decorator form
    def decorator(cls_or_instance):
        # If it's a class (not an instance), instantiate it
        instance = cls_or_instance() if isinstance(cls_or_instance, type) else cls_or_instance
        _rust_register_type(name, instance)
        return cls_or_instance

    return decorator

remove_type builtin

remove_type(name)

Remove a specific custom type handler.

clear_type_handlers builtin

clear_type_handlers()

Clear all custom type handlers.

register_schema builtin

register_schema(name, schema_yaml)

Register a YAML Schema Language schema under a name.

schema_yaml is a schema definition in YAML format:

name: myapp
extends: core
rules:
  - pattern: "^0x[0-9a-fA-F]+$"
    type: int
Once registered, the schema can be used as YAML(schema="myapp").

list_schemas builtin

list_schemas()

List all registered schema names (built-in + custom).

Returns the four built-in schemas (failsafe, json, core, yaml1.1) plus any schemas registered via register_schema() / load_schema().

load_schema builtin

load_schema(name, path)

Register a YAML Schema Language schema from a file.

Reads the schema definition from path (a YAML file with name/extends/rules structure) and registers it under name. Equivalent to calling register_schema(name, open(path).read()) but handles file I/O in Rust.

compliance_report

compliance_report(suite_dir=None)

Run the YAML Test Suite and return a compliance report.

The suite data is a dev artifact (Reference/yaml-test-suite), not bundled in the wheel; pass suite_dir when it lives elsewhere.

Source code in python/pyrs_yaml/compliance.py
263
264
265
266
267
268
269
270
271
272
273
274
275
def compliance_report(suite_dir: str | None = None) -> dict[str, Any]:
    """Run the YAML Test Suite and return a compliance report.

    The suite data is a dev artifact (``Reference/yaml-test-suite``), not
    bundled in the wheel; pass ``suite_dir`` when it lives elsewhere.
    """
    if suite_dir is None:
        suite_dir = DEFAULT_SUITE_DIR
    if not Path(suite_dir).exists():
        raise FileNotFoundError(
            f"yaml-test-suite not found at {suite_dir}; clone https://github.com/yaml/yaml-test-suite into Reference/"
        )
    return compute_compliance(suite_dir)

validate_custom_types builtin

validate_custom_types(obj)

Validate a Python object against all registered CustomType validators.

Recursively walks dicts and lists. For each value that matches a registered type's python_type, calls the handler's validate method. Raises ValueError if any value fails validation.

detect_language builtin

detect_language()

Detect the system default language.

get_language builtin

get_language()

Return the current error message language.

set_language builtin

set_language(lang)

Set the error message language.

list_languages builtin

list_languages()

List supported language codes.

negotiate_language builtin

negotiate_language(user_locales, default='en')

Negotiate a language from user locale list and default.

discover_plugins

discover_plugins(force=False)

Re-discover third-party plugins via entry_points.

By default, only plugins not yet loaded are processed. Set force=True to re-run discovery for all plugins (including those that previously failed or were already loaded).

Source code in python/pyrs_yaml/plugins/__init__.py
58
59
60
61
62
63
64
65
66
def discover_plugins(force: bool = False) -> None:
    """Re-discover third-party plugins via entry_points.

    By default, only plugins not yet loaded are processed. Set ``force=True``
    to re-run discovery for all plugins (including those that previously
    failed or were already loaded).
    """
    _discovery_errors.clear()
    _discover()

get_plugin builtin

get_plugin(tag)

Get metadata for a registered plugin by tag.

Returns (tag, python_type) or None if the tag is not registered.

list_plugins builtin

list_plugins()

List all registered custom type plugins with their metadata.

Returns a list of (tag, python_type) tuples for every registered CustomType handler.

get_discovery_errors

get_discovery_errors()

Return a list of error messages from the last plugin discovery run.

Source code in python/pyrs_yaml/plugins/__init__.py
69
70
71
def get_discovery_errors() -> list[str]:
    """Return a list of error messages from the last plugin discovery run."""
    return list(_discovery_errors)