跳转至

模块参考

pyrs_yaml 模块的完整 API 参考。

版本兼容

pyrs-yaml 以 ABI3 wheel 格式构建,单个 wheel 支持 Python 3.8 到 3.15,无需重新编译。

核心函数

parse()

将 YAML 字符串或字节解析为 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

参数:

  • yaml — str 或 bytes 的 YAML 内容
  • resolve_merges — 解析后是否解析合并键 (<<: *alias)(默认:True)
  • schema — Schema 名称 ("core", "json", "failsafe", "yaml1.1" 或已注册的自定义名称),或内联 schema dict(参见 YAML Schema Language)
  • max_depth — 最大嵌套深度(默认:1000)
  • allow_duplicate_keys — 是否允许重复映射键(默认:None,等同 "as_is")
  • duplicate_keys — 一个映射里出现两个被 YAML 算作同一个的键时,读取怎么做(默认:"as_is")。"as_is" 按身份类别给出它一直给出的答案:标量键冲突、普通写法与引号写法的冲突都被拒绝;第二个空键或合并键折叠进第一个槽位;带 tag 的两个键在任何取值下都算两个键。"error" 连默认被豁免的类别也拒绝;"last_wins" 静默折叠到后一对,这就是 allow_duplicate_keys=True 的意思;"first_wins" 保留前一对的值,并把被折叠那对的注释与锚点定义交给留下来的那个键。同时传入本项和 allow_duplicate_keys 会被拒绝,而不是按优先级决出。
  • honor_version_directive — 对显式 %YAML 指令做版本协商(默认:False)。取 True 时,声明 %YAML 1.1 的文档按 YAML 1.1 档位解析并重新发射该指令;显式 schema 仍然优先。

返回值: 包含解析后 YAML 的 YamlDocument

引发:

  • YamlParseError — 无效的 YAML 语法
  • YamlTypeError — 未找到指定的 Schema
  • TypeError — 输入不是 str 或 bytes

示例:

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()

解析 YAML 文件。

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

参数:

  • path — YAML 文件的路径
  • schema — Schema 名称或内联 dict(默认:"core")
  • max_depth — 最大嵌套深度(默认:1000)
  • allow_duplicate_keys — 是否允许重复映射键(默认:None,等同 "as_is")
  • duplicate_keys — 一个映射里出现两个被 YAML 算作同一个的键时,读取怎么做(默认:"as_is")。"as_is" 按身份类别给出它一直给出的答案:标量键冲突、普通写法与引号写法的冲突都被拒绝;第二个空键或合并键折叠进第一个槽位;带 tag 的两个键在任何取值下都算两个键。"error" 连默认被豁免的类别也拒绝;"last_wins" 静默折叠到后一对,这就是 allow_duplicate_keys=True 的意思;"first_wins" 保留前一对的值,并把被折叠那对的注释与锚点定义交给留下来的那个键。同时传入本项和 allow_duplicate_keys 会被拒绝,而不是按优先级决出。
  • honor_version_directive — 对显式 %YAML 指令做版本协商(默认:False)。取 True 时,声明 %YAML 1.1 的文档按 YAML 1.1 档位解析并重新发射该指令;显式 schema 仍然优先。

返回值: YamlDocument

引发:

  • IOError — 文件未找到或无法读取
  • YamlParseError — 无效的 YAML

示例:

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

parse_all_docs()

从字符串解析多个 YAML 文档。

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]

参数:

  • yaml — str 或 bytes 的 YAML 内容
  • resolve_merges — 解析后是否解析合并键 (<<: *alias)(默认:True)
  • schema — Schema 名称 ("core", "json", "failsafe", "yaml1.1" 或已注册的自定义名称),或内联 schema dict(参见 YAML Schema Language)
  • max_depth — 最大嵌套深度(默认:1000)
  • allow_duplicate_keys — 是否允许重复映射键(默认:None,等同 "as_is")
  • duplicate_keys — 一个映射里出现两个被 YAML 算作同一个的键时,读取怎么做(默认:"as_is")。"as_is" 按身份类别给出它一直给出的答案:标量键冲突、普通写法与引号写法的冲突都被拒绝;第二个空键或合并键折叠进第一个槽位;带 tag 的两个键在任何取值下都算两个键。"error" 连默认被豁免的类别也拒绝;"last_wins" 静默折叠到后一对,这就是 allow_duplicate_keys=True 的意思;"first_wins" 保留前一对的值,并把被折叠那对的注释与锚点定义交给留下来的那个键。同时传入本项和 allow_duplicate_keys 会被拒绝,而不是按优先级决出。
  • honor_version_directive — 对显式 %YAML 指令做版本协商(默认:False)。取 True 时,声明 %YAML 1.1 的文档按 YAML 1.1 档位解析并重新发射该指令;显式 schema 仍然优先。

返回值: YamlDocument 对象列表

示例:

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

PyYAML 兼容函数

safe_load()

解析 YAML 并返回原生 Python 类型。

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]

参数:

  • yaml — str 或 bytes 的 YAML 内容
  • schema — Schema 名称 ("core", "json", "failsafe", "yaml1.1" 或已注册的自定义名称),或内联 schema dict(参见 YAML Schema Language)
  • max_depth — 最大嵌套深度(默认:1000)
  • allow_duplicate_keys — 是否允许重复映射键(默认:None,等同 "as_is")
  • duplicate_keys — 一个映射里出现两个被 YAML 算作同一个的键时,读取怎么做(默认:"as_is")。"as_is" 按身份类别给出它一直给出的答案:标量键冲突、普通写法与引号写法的冲突都被拒绝;第二个空键或合并键折叠进第一个槽位;带 tag 的两个键在任何取值下都算两个键。"error" 连默认被豁免的类别也拒绝;"last_wins" 静默折叠到后一对,这就是 allow_duplicate_keys=True 的意思;"first_wins" 保留前一对的值,并把被折叠那对的注释与锚点定义交给留下来的那个键。同时传入本项和 allow_duplicate_keys 会被拒绝,而不是按优先级决出。
  • honor_version_directive — 对显式 %YAML 指令做版本协商(默认:False)。取 True 时,声明 %YAML 1.1 的文档按 YAML 1.1 档位解析并重新发射该指令;显式 schema 仍然优先。

等价于: PyYAML 的 yaml.safe_load()

示例:

data = pyrs_yaml.safe_load("key: value")  # {'key': 'value'}

safe_loads()

解析多个 YAML 文档。

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]]

参数:

  • yaml — str 或 bytes 的 YAML 内容
  • schema — Schema 名称 ("core", "json", "failsafe", "yaml1.1" 或已注册的自定义名称),或内联 schema dict(参见 YAML Schema Language)
  • max_depth — 最大嵌套深度(默认:1000)
  • allow_duplicate_keys — 是否允许重复映射键(默认:None,等同 "as_is")
  • duplicate_keys — 一个映射里出现两个被 YAML 算作同一个的键时,读取怎么做(默认:"as_is")。"as_is" 按身份类别给出它一直给出的答案:标量键冲突、普通写法与引号写法的冲突都被拒绝;第二个空键或合并键折叠进第一个槽位;带 tag 的两个键在任何取值下都算两个键。"error" 连默认被豁免的类别也拒绝;"last_wins" 静默折叠到后一对,这就是 allow_duplicate_keys=True 的意思;"first_wins" 保留前一对的值,并把被折叠那对的注释与锚点定义交给留下来的那个键。同时传入本项和 allow_duplicate_keys 会被拒绝,而不是按优先级决出。
  • honor_version_directive — 对显式 %YAML 指令做版本协商(默认:False)。取 True 时,声明 %YAML 1.1 的文档按 YAML 1.1 档位解析并重新发射该指令;显式 schema 仍然优先。

等价于: PyYAML 的 yaml.safe_loads()

safe_dump()

将 Python 对象序列化为 YAML。

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

等价于: PyYAML 的 yaml.safe_dump()

支持的输入类型: dict, list, str, int, float, bool, None,以及 numpy.ndarray(所有维度和数值 dtype:int8/16/32/64, uint8/16/32/64, float32/64, complex64/128, bool)

safe_dumps()

safe_dump() 的别名。

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

:material-json: 转换函数

from_dict()

将 Python dict 转换为 YAML 字符串。dict 的值中可以包含 numpy.ndarray。

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

from_json()

将 JSON 字符串转换为 YAML 字符串。

from_json(json_str: str) -> str

dump_file()

将 Python 对象序列化为 YAML 并写入文件。接受 dict、list 或 numpy.ndarray。

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

Pydantic 集成

dump_pydantic()

将 Pydantic 模型序列化为 YAML 字符串。

dump_pydantic(model: BaseModel) -> str

使用 model_dump(mode='json') 保持字符串类型(例如 "10001" 的邮政编码保持为字符串),然后委托给 safe_dump。

引发:

  • ImportError — 未安装 pydantic
  • TypeError — model 不是 Pydantic 的 BaseModel 实例

示例:

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()

解析 YAML 字符串并针对 Pydantic 模型进行验证。

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

参数:

  • model — Pydantic 的 BaseModel 子类
  • src — 要解析的 YAML 字符串
  • **yaml_kwargs — 转发给 YAML() 构造函数的关键字参数

引发:

  • ImportError — 未安装 pydantic
  • TypeError — model 不是 Pydantic 的 BaseModel 子类
  • pydantic.ValidationError — 解析的数据未通过模型验证

示例:

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

PyrsYamlConfigSettingsSource

基于 pyrs-yaml 的 pydantic-settings YAML 配置来源类。pydantic_settings.YamlConfigSettingsSource 的即插即用替代品,使用 pyrs-yaml 而非 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,
)

从 SettingsConfigDict(yaml_file=...)(或直接传入)声明的 YAML 文件加载设置,并用 pyrs-yaml 解析器(YAML 1.2 核心 schema)解析。环境变量与 dotenv 覆盖、yaml_config_section(支持点号嵌套路径)、多文件 deep_merge、yaml_file_encoding 等其他 pydantic-settings 功能均与 YamlConfigSettingsSource 行为一致。

异常:

  • ImportError — 未安装 pydantic-settings 时抛出(安装 pyrs-yaml[settings])

示例:

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),
        )

注意: 该类采用惰性导出——import pyrs_yaml 不依赖 pydantic-settings。在未安装 pydantic-settings 时访问 pyrs_yaml.PyrsYamlConfigSettingsSource 会抛出带有安装提示的 ImportError。

标签注册表

register_tag()

注册自定义标签处理器。支持装饰器和命令式两种形式。

register_tag(name: str, handler: Callable | None = None, priority: int = 0) -> Callable
@pyrs_yaml.register_tag("!custom")
def handler(node):
    return f"custom:{node}"
pyrs_yaml.register_tag("!custom", handler_fn, priority=1)

remove_tag()

移除标签处理器。

remove_tag(name: str) -> None

clear_tag_handlers()

移除所有已注册的标签处理器。

clear_tag_handlers() -> None

YAML Schema Language

定义自定义 Schema,控制纯标量如何解析为 Python 类型。

register_schema()

注册一个自定义 Schema。

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

参数:

  • name — Schema 名称
  • schema_yaml — YAML 字符串(包含 extends、rules、validate 键);内联 dict 由 YAML(schema=...) 接受

示例:

import pyrs_yaml

# 从 YAML 字符串注册自定义 Schema
pyrs_yaml.register_schema(
    "hex",
    """
name: hex
extends: core
rules:
  - pattern: ^0x[0-9a-fA-F]+$
    type: int
""",
)

# 使用自定义 Schema
y = pyrs_yaml.YAML(schema="hex")
doc = y.parse("addr: 0xFF")
assert doc.get("addr") == 255

d = pyrs_yaml.safe_load("addr: 0x1F", schema="hex")
assert d["addr"] == 31

内联 Schema dict

直接传入 dict 代替注册:

d = pyrs_yaml.safe_load(
    "addr: 0xFF",
    schema={
        "extends": "core",
        "rules": [{"pattern": "^0x[0-9a-fA-F]+$", "type": "int"}],
    },
)
  • extends — 可选的基 Schema(core、json、failsafe、yaml1.1)
  • rules — 有序的 {pattern, type} 列表;首个匹配生效
  • 支持的类型:null、bool、int、float、str
  • 内置 Core Schema 仍使用零成本 match 分发(不受影响)
  • 文件 I/O — load_schema(name, path) 从 YAML 文件加载 Schema;list_schemas() 返回所有已注册的 Schema

社区插件

定义自定义 YAML 节点类型,集成序列化和反序列化。

CustomType

自定义类型的基类。

class CustomType:
    python_type: type

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

register_type()

注册自定义类型。

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

示例:

from datetime import datetime


class TimestampType(pyrs_yaml.CustomType):
    python_type = datetime

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

    def to_yaml(self, obj) -> str:
        return obj.isoformat()


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

# 加载:带标签的标量 → Python 对象
doc = pyrs_yaml.parse("when: !timestamp 2026-08-11T10:30:00")
assert isinstance(doc.get("when"), datetime)

# 导出:Python 对象 → 带标签的标量
data = {"ts": datetime(2026, 8, 11, 10, 30)}
out = pyrs_yaml.safe_dump(data)
# out 包含:!!timestamp 2026-08-11T10:30:00
方法 描述
can_parse(node) 该类型是否处理给定的 AST 节点
from_yaml(value) 将 YAML 字符串转换为 Python 对象
to_yaml(obj) 将 Python 对象转换为 YAML 字符串
validate(obj) 校验 Python 对象(返回 bool)

remove_type()

移除已注册的类型。

remove_type(name: str) -> None

clear_type_handlers()

移除所有已注册的类型处理器。

clear_type_handlers() -> None

合规性

compliance_report()

计算 YAML 测试套件的合规性报告。

compliance_report() -> dict

返回 YAML 测试套件的通过率及每个测试的结果。

流式事件

parse_stream()

增量解析一份文档,产出原始事件字典。

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

返回一个 StreamIterator,每步产出一个事件字典。与 YAML().load_stream()(解析为 Python 值)不同,这暴露了原始令牌流。

format 决定由哪个生产者来读:yaml(默认)、json、jsonc、json5 或 toml,而每个生产者报告的都是同一套词汇表,因此字典始终是那九个键(type、value、style、anchor、tag、line、column、offset、end)。offset 与 end 是该事件自身令牌在源码中的字节区间——source.encode()[event["offset"]:event["end"]] 就能把它解码出来——而只记录位置的生产者,例如每一个 TOML 事件,其 end 等于 offset。一个 comment 事件还带着第十个键 owner,指名这条注释被归档在哪个节点的哪个槽位下。某个格式无话可说的字段保持 None:anchor 是 YAML 自己的,alias 在其余格式里从不出现;TOML 的字面量 '…' 与基础串 "…" 读起来一样,因为用的是哪种引号并不留在中间表示里。JSON 或 TOML 的流只承载一个文档,而接受还是拒绝由同一个扫描器判定,与走树那条路给出的答复一致。逐键的表格见 流式解析。

YamlStream

YamlStream 类是一个惰性事件迭代器,由 YAML().load_stream() 和 YAML().load_stream_file() 返回。它逐个产出解析后的事件字典,无需将整个文档加载到内存中。

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

参见 YamlStream 了解完整的 API 详情。

异步函数

使用 asyncio.run_in_executor 的异步 I/O 包装器。在事件循环上下文中不阻塞。

safe_dumps_async()

将 Python 对象序列化为 YAML 字符串(异步)。

async def safe_dumps_async(data: Any) -> str

safe_dump_async()

将 Python 对象以 YAML 格式输出到 stdout(异步)。

async def safe_dump_async(data: Any) -> None

safe_loads_async()

将 YAML 字符串解析为原生 Python 对象(异步)。

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

safe_load_async()

将 YAML 字符串解析为原生 Python 对象(异步)。

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

示例:

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 Front Matter

read_markdown()

从 Markdown 文件提取 YAML Front Matter。

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

返回值: (frontmatter_dict, content_string)。没有Front Matter时,frontmatter 为 None。

read_markdown_str()

从 Markdown 字符串提取 YAML Front Matter。

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

i18n 函数

set_language()

设置错误消息的语言。

set_language(lang: str) -> None

支持:"en", "zh-CN", "ja-JP", "ko-KR"

get_language()

获取当前语言。

get_language() -> str

list_languages()

列出所有支持的语言。

list_languages() -> list[str]

detect_language()

从环境变量自动检测用户的首选语言。

detect_language() -> str

negotiate_language()

BCP 47 语言协商。

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

异常

  • YamlParseError — YAML 解析错误(继承自 ValueError)
  • YamlSerializeError — YAML 序列化错误(继承自 ValueError)
  • YamlTypeError — 类型转换错误(继承自 TypeError)
  • YamlValidateError — JSON Schema 验证错误(继承自 ValueError)
  • YamlEditError — 就地编辑错误(继承自 ValueError)
  • YamlPathError — YAML 路径错误(继承自 ValueError)
  • YamlDocumentError — 过期的 Node 访问错误(继承自 Exception)
  • YamlDuplicateKeyError — 重复的映射键(继承自 ValueError)
  • YamlMaxDepthError — 超过最大嵌套深度(继承自 ValueError)
  • YamlTagError — 标签处理器错误(继承自 ValueError)
  • YamlTagSkip — 将节点交给下一个处理器的控制流哨兵(继承自 YamlTagError)

Document.validate() 全程在这个家族之内回答。它把规则委托给 jsonschema,这里没有任何东西会安装它 — 该包只依赖 typing-extensions,其 extras 是 cli、pydantic 与 settings — 所以校验前请先运行 pip install jsonschema。没有可导入的求值器时,这次调用抛出 YamlValidateError,其消息点名这条安装途径并带上 import 错误,哪怕文档本会通过那份 schema。以文本给出的 schema 是本包自己的门:求值之前先由 json.loads 读取,不是 JSON 的文本以 YamlValidateError 被拒绝(schema text must be JSON (…); pass the schema as a dict if it is not JSON),所以 YAML 拼法也留在了家族之内。求值器不随库发布是已知边界,面向用户的说明写在快速开始与自定义 Schema。

参见 异常 页面了解完整详情。

版本

__version__ = "0.19.1"

生成的 API 参考

以下内容由 mkdocstrings 从库自身的 docstring 与生成的类型存根渲染,签名来自代码,不是手抄。

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)