コンテンツにスキップ

モジュールリファレンス

バージョン互換性

pyrs-yaml は ABI3 アプローチにより、単一のホイールで Python 3.8 から 3.15 まで対応しています。再コンパイルは不要です。

pyrs_yaml モジュールの完全な API リファレンス。

コア関数

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 — スキーマ名 ("core", "json", "failsafe", "yaml1.1" または登録済みカスタム名)、またはインラインスキーマ dict(YAML スキーマ言語 参照)
  • max_depth — 最大ネスト深度 (デフォルト: 1000)
  • allow_duplicate_keys — 重複マッピングキーを許可するかどうか (デフォルト: None、"as_is" と同じ)
  • duplicate_keys — 一つのマッピングに YAML が同じと数えるキーが二つあるとき、読み手がどう動くか (デフォルト: "as_is")。"as_is" は身分のクラスごとにこれまでの答を返す: スカラーの衝突と普通/引用表記の衝突は拒否、二つ目の null キーとマージキーは最初の枠に畳み込み、タグはどの値でも二つのキーを区別する。"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 — 指定されたスキーマが見つかりません
  • 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 ファイルへのパス

戻り値: 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 — スキーマ名 ("core", "json", "failsafe", "yaml1.1" または登録済みカスタム名)、またはインラインスキーマ dict(YAML スキーマ言語 参照)
  • max_depth — 最大ネスト深度 (デフォルト: 1000)
  • allow_duplicate_keys — 重複マッピングキーを許可するかどうか (デフォルト: None、"as_is" と同じ)
  • duplicate_keys — 一つのマッピングに YAML が同じと数えるキーが二つあるとき、読み手がどう動くか (デフォルト: "as_is")。"as_is" は身分のクラスごとにこれまでの答を返す: スカラーの衝突と普通/引用表記の衝突は拒否、二つ目の null キーとマージキーは最初の枠に畳み込み、タグはどの値でも二つのキーを区別する。"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 — スキーマ名 ("core", "json", "failsafe", "yaml1.1" または登録済みカスタム名)、またはインラインスキーマ dict(YAML スキーマ言語 参照)
  • max_depth — 最大ネスト深度 (デフォルト: 1000)
  • allow_duplicate_keys — 重複マッピングキーを許可するかどうか (デフォルト: None、"as_is" と同じ)
  • duplicate_keys — 一つのマッピングに YAML が同じと数えるキーが二つあるとき、読み手がどう動くか (デフォルト: "as_is")。"as_is" は身分のクラスごとにこれまでの答を返す: スカラーの衝突と普通/引用表記の衝突は拒否、二つ目の null キーとマージキーは最初の枠に畳み込み、タグはどの値でも二つのキーを区別する。"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 — スキーマ名 ("core", "json", "failsafe", "yaml1.1" または登録済みカスタム名)、またはインラインスキーマ dict(YAML スキーマ言語 参照)
  • max_depth — 最大ネスト深度 (デフォルト: 1000)
  • allow_duplicate_keys — 重複マッピングキーを許可するかどうか (デフォルト: None、"as_is" と同じ)
  • duplicate_keys — 一つのマッピングに YAML が同じと数えるキーが二つあるとき、読み手がどう動くか (デフォルト: "as_is")。"as_is" は身分のクラスごとにこれまでの答を返す: スカラーの衝突と普通/引用表記の衝突は拒否、二つ目の null キーとマージキーは最初の枠に畳み込み、タグはどの値でも二つのキーを区別する。"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

pydantic-settings の YAML ソースを pyrs-yaml で実現するクラス。pydantic_settings.YamlConfigSettingsSource のドロップイン代替で、PyYAML の代わりに pyrs-yaml をパーサとして使用します。

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 コアスキーマ)で解析します。環境変数・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 スキーマ言語

カスタムスキーマを定義して、プレーンスカラーが Python 型にどのように解決されるかを制御します。

register_schema()

カスタムスキーマを登録します。

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

パラメーター:

  • name — スキーマ名
  • schema_yaml — YAML 文字列(extends、rules、validate キーを含む)。インライン dict は YAML(schema=...) の方が受け付けます

例:

import pyrs_yaml

# YAML 文字列からカスタムスキーマを登録
pyrs_yaml.register_schema(
    "hex",
    """
name: hex
extends: core
rules:
  - pattern: ^0x[0-9a-fA-F]+$
    type: int
""",
)

# カスタムスキーマを使用
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

インラインスキーマ dict

登録せずに dict を直接渡す:

d = pyrs_yaml.safe_load(
    "addr: 0xFF",
    schema={
        "extends": "core",
        "rules": [{"pattern": "^0x[0-9a-fA-F]+$", "type": "int"}],
    },
)
  • extends — オプションのベーススキーマ(core、json、failsafe、yaml1.1)
  • rules — 順序付きの {pattern, type} リスト;最初にマッチしたものが適用
  • 対応型:null、bool、int、float、str
  • 組み込み Core スキーマは引き続きゼロコスト match ディスパッチを使用(影響なし)
  • ファイル I/O — load_schema(name, path) で YAML ファイルからスキーマを読み込み;list_schemas() で登録済みの全スキーマを取得

コミュニティプラグイン

カスタム 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()

ドキュメントをインクリメンタルにパースし、生のイベント dict を生成します。

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

各ステップで 1 つのイベント dict を生成する StreamIterator を返します。YAML().load_stream()(Python 値に解決される)とは異なり、生のトークンストリームを公開します。

format はどの生産者が読むかを決めます — yaml(既定)、json、jsonc、json5、toml。どの生産者も同じ語彙を報告するので、dict は常に同じ 9 つのキー(type、value、style、anchor、tag、line、column、offset、end)を持ちます。offset と end はそのイベント自身のトークンのソースバイト範囲です — source.encode()[event["offset"]:event["end"]] でデコードできます。位置だけを記録する生産者では(すべての TOML イベントがそうです)、end は offset と等しくなります。comment イベントは 10 番目のキー owner を持ち、注釈がどのノードのどのスロットにまとめられているかを名乗ります。そのフォーマットが何も言えないフィールドは None のままです。anchor も alias も YAML 固有で、他の形式では現れません。TOML のリテラル '…' は基本文字列 "…" と同じ読みになります — どちらの引用符を使ったかは中間表現に残らないためです。JSON と TOML のストリームは 1 つのドキュメントだけを運び、採用か拒否かの判定はツリーを歩く経路と同じ答えになります。同じスキャナーが応えるからです。キーごとの表は ストリーミングイベント を参照してください。

YamlStream

YamlStream クラスは、YAML().load_stream() と YAML().load_stream_file() が返す遅延イベントイテレータです。ドキュメント全体をメモリに読み込まずに、パース済みのイベント dict を一度に 1 つ生成します。

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

完全な API の詳細は YamlStream を参照してください。

非同期関数

asyncio.run_in_executor を使用した非同期 I/O ラッパー。イベントループコンテキストではノンブロッキング。

safe_dumps_async()

Python オブジェクトを YAML 文字列にシリアライズ (非同期)。

async def safe_dumps_async(data: Any) -> str

safe_dump_async()

Python オブジェクトを stdout に YAML として出力 (非同期)。

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 のみに依存し、extra は cli、pydantic、settings です——だから検証の前に pip install jsonschema を実行して ください。評価器が import できないとき、この呼び出しはそのインストール経路を名乗り import エラーを添えた YamlValidateError を投げます。スキーマなら通す文書でも同じです。テキストで 与えた schema はこのパッケージ自身の扉で、評価の前に json.loads で読まれ、JSON でない テキストは YamlValidateError (schema text must be JSON (…); pass the schema as a dict if it is not JSON)で拒否されるため、 YAML の綴りも一族の内側に留まります。評価器が出荷物に無いことは既知の境界で、利用者向けの 説明は クイックスタート と カスタムスキーマ に置いています。

詳細は 例外 ページを参照してください。

バージョン

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