コンテンツにスキップ

YamlDocument クラス

概要

YamlDocument は pyrs-yaml のコアクラスで、解析済みの YAML ドキュメントを保持します。IndexMap を使用したカスタム AST により、100% ラウンドトリップ、完全なキー順序保持、ネストされたコメントの保持、詳細なメタデータを実現します。

class YamlDocument:
    """pyrs-yaml のコアクラス。"""

    # ... C 拡張で実装 ...

コンストラクター

YamlDocument()

内部コンストラクター。ユーザーが直接呼び出すことはありません。pyrs_yaml.parse() から返されます。

プロパティ

  • version — YAML ドキュメントバージョン
  • schema — スキーマ(core, failsafe, json)
  • tags — タグ一覧
  • anchors — アンカー一覧
  • source — YAML ソーステキスト

メソッド

to_yaml()

ドキュメントを YAML 文字列に変換します。

to_yaml(
    indent: int = 2,
    allow_unicode: bool = True,
    default_flow_style: bool = False,
    sort_keys: bool = False,
    width: int = 80,
    resolve_aliases: bool = True,
    strip_comments: bool = False,
    preserve_quotes: bool = True,
) -> str

パラメータ:

  • indent — インデントスペース数(デフォルト: 2)
  • allow_unicode — Unicode 文字を許可(デフォルト: True)
  • default_flow_style — デフォルトでフロースタイルを使用(デフォルト: False)
  • sort_keys — キーをソート(デフォルト: False)。アンカー名をローカルで定義しローカルで使うマッピングはソース順を保ち、ソートが別名を解決先の &name より上に書くことはありません
  • width — 折り返し幅(デフォルト: 80)
  • resolve_aliases — エイリアスを解決(デフォルト: True)
  • strip_comments — コメントを除去(デフォルト: False)
  • preserve_quotes — クォートを保持(デフォルト: True)

戻り値: YAML 文字列

例:

doc = pyrs_yaml.parse("key: value\n# comment")
yaml_str = doc.to_yaml()

to_yaml_with_options()

カスタムオプションで YAML に変換します。

to_yaml_with_options(
    indent_size: int = 2,
    explicit_start: bool = False,
    explicit_end: bool = False,
    sort_keys: bool = False,
    note_placement: str = "note_first",
) -> str

パラメータ:

  • indent_size — インデントレベルごとのスペース数 (デフォルト: 2)
  • explicit_start — ドキュメント先頭に --- を追加 (デフォルト: False)
  • explicit_end — ドキュメント末尾に ... を追加 (デフォルト: False)
  • sort_keys — キーをアルファベット順にソート (デフォルト: False)。アンカー名をローカルで定義しローカルで使うマッピングはソース順を保ち、ソートが別名を解決先の &name より上に書くことはありません
  • note_placement — 備考が自分の行に乗れず、直上が &a / !tag ヘッダー行になるときの位置: note_first(既定)はヘッダーの上に書きます。読み戻しもそこへまとめるので、最初の出力で収束します。header_first はヘッダーと本文の間に留めます。それ以外の値は拒否されます

例:

yaml_str = doc.to_yaml_with_options(
    indent_size=4,
    explicit_start=True,
    sort_keys=True,
)

to_dict()

Python dict/list に変換します。エイリアス参照を解決し、ネイティブ Python タイプを返します。同じ解決は mapping の key にも等しく適用されます — ~: 1 の key は None、1: a の key は整数 1。同じテキストなら : のどちら側にあっても同じ型になります。

to_dict() -> dict[Any, Any] | list[Any]

戻り値: 辞書またはリスト

例:

doc = pyrs_yaml.parse("key: value")
data = doc.to_dict()  # {'key': 'value'}

get()

トップレベルのマッピングキーによるリテラルキー検索で値を取得します(__getitem__/__setitem__ と一貫)。キーは .、[、]、$ を含めても常に文字どおりのキーとして扱われ、パスとして解釈されません。

get(key: str, default: Any = None) -> Any

戻り値: 値、見つからない場合はデフォルト

パスアクセス

JSONPath スタイルのアクセスには find() / node() / set() を使ってください($.a.b、$.items[-1] 等)。

root_type()

ルートノードの型を文字列で取得します。

root_type() -> str

戻り値: "scalar"、"mapping"、"sequence"、"null" のいずれか。

"alias" はバインディングがエイリアスルート用に携えている綴りですが、どの文書の読み取りでも そこには届きません:エイリアスには同じ文書内のより前にそのアンカーが必要なので、ルートの エイリアスはパーサーに拒否されます。pyrs_yaml.parse("*x\n") は YamlParseError: YAML parse error: while parsing node, found unknown anchor at char 0 line 1 column 1 と答え、文書をまたぐ形 "--- &a 1\n--- *a\n" は 2 行目で同じように拒否されます。

例:

print(doc.root_type())  # "mapping"

to_json()

ドキュメントを JSON 文字列にシリアライズします。

to_json(indent: int = 2) -> str

戻り値: JSON 文字列

validate()

JSON Schema に基づいてドキュメントの内容を検証します。

validate(schema: str | dict[str, Any]) -> None

スロー:

  • YamlValidateError — ドキュメントがスキーマに適合しないか、スキーマ引数が使えません。JSON ではない str は schema text must be JSON (…); pass the schema as a dict if it is not JSON で拒否され、 str でもマッピングでもない引数も同じくここに届き、エンジンの文をそのテキストにします: doc.validate(3) は TypeError: argument of type 'int' is not iterable と答えます

評価は Python の jsonschema パッケージへ委譲され、本プロジェクトが公開するどの extra もそれを インストールしません:検証の前に pip install jsonschema を実行してください。jsonschema が import できないときも doc.validate({"type": "object"}) は YamlValidateError で答え、その メッセージはこのインストール経路を名乗り import エラーを添えます。再現とともに 例外 — YamlValidateError に記録しています。

flush_source()

flush_source() -> None

編集が発生したあと、AST を source へ遅延再シリアライズして現在のツリーを反映します。変更のたびにフル ダンプを強制しません。

reparse()

保存されたソーステキストをその場で再パースし、スキーマやマージ動作の変更を可能にします。

reparse(resolve_merges: bool = True, schema: str | None = None, honor_version_directive: bool | None = None) -> None

パラメータ:

  • resolve_merges — <<: *alias マージキーを解決するかどうか (デフォルト: True)
  • schema — 型解決スキーマ: "core", "json", "failsafe", または "yaml1.1"。None は文書を読み込 んだときのスキーマのままです。
  • honor_version_directive — 宣言された %YAML のバージョン交渉。True なら %YAML 1.1 を宣言する文 書は 1.1 プロファイルで解決され、ディレクティブも再出力されます。False は宣言を無視して選んだ スキーマを保ちます。None は文書の現在の設定を保ちます。

スロー:

  • TypeError — ソーステキストが保存されていない
  • YamlParseError — 再パースに失敗

例:

doc = pyrs_yaml.parse("x: on")
print(doc.get("x"))  # "on" (string, core schema)

doc.reparse(schema="yaml1.1")
print(doc.get("x"))  # True (bool, yaml1.1 schema)

source()

このドキュメントの作成に使用された元の YAML ソーステキストを返します。ドキュメントがその場で編集された場合、ソースは最初のアクセス時に現在のツリーから遅延して再シリアライズされます。

source() -> str

戻り値: YAML 文字列。parse() で作成されていない場合(例: from_dict())は空文字列。

例:

doc = pyrs_yaml.parse("key: value")
print(doc.source())  # "key: value"

編集メソッド

アトミック編集

pyrs-yaml の編集操作はすべてアトミックです。失敗した場合、ドキュメント(リビジョンを含む)は変更されません。

ドキュメントをその場で編集し、すべてのメタデータ(コメント、アンカー、タグ、スタイル)を保持します。編集は JSONPath スタイルのパス($.a.b、$.items[0])でノードを特定します。

set()

パスで値を置き換えます。

set(path: str, value: Any, create_missing: bool = False) -> None
  • スカラー、dict、list、tuple をサポート — tuple は受け入れられ、list と同じくシーケンスとして書き出されます
  • 既存のスカラーを置換する場合、対象のメタデータが保持されます;パスが存在しない場合はマッピングの末尾に新しいキーを追加
  • 空のドキュメント("" からパース)にパスを設定すると、マッピングルートが自動的に作成されます
  • create_missing=True を指定すると、不足している中間マッピングキーが自動的に作成されます

スロー:

  • YamlPathError — 不正なパス(ワイルドカード/.. は拒否されます)
  • YamlEditError — 適用できないパスのステップで、メッセージがそれを名乗ります:エイリアスを 経由するステップは edit failed: cannot-edit-alias、スカラーや形の違うコンテナに入る ステップは create-needs-mapping、create_missing=True がスカラーと出会う場合は cannot-descend-into-scalar:<segment>、書き込むキーより前に欠けているキーなら missing-path:<key>、シーケンスの向こうのインデックスなら index-out-of-range-edit:<index>。 最後のキーの欠落は拒否ではなく——parse("a: 1\n").set("$.zz", 3) は a: 1\nzz: 3\n を 出力します——生きているアンカーの書き込みも拒否ではありません:base: &x 1\nuse: *x\n での set("$.base", 2) は base: &x 2\nuse: *x\n を再出力し、&x をそのエイリアスがいまだ 見つける位置に保ちます
  • YamlTypeError — 書き手が知らない Python 型の値。tuple は受け入れられ、シーケンスとして 書き出され、bytes は !!binary として受け入れられます

呼び出しごとに実測した完全な語彙は編集理由トークンにあります。

例:

doc = pyrs_yaml.parse("a:\n  b: 1")
doc.set("$.a.b", 42)
doc.set("$.a.c", True)  # 新しいキーを追加
doc.set("$", {"x": 1})  # ルート全体を置換

# create_missing で不足キーを自動作成
doc.set("$.b.c.d", 2, create_missing=True)

walk()

AST の深さ優先・先行順の走査で、Node オブジェクトを生成します。

walk() -> Generator[Node, None, None]

Node.walk() とは異なり、このメソッドはRust バックエンドです — AST を Python dict に変換せずに直接走査するため、大規模ドキュメントで大幅に高速です。

生成するもの: ルートを含む、ドキュメントツリー内のすべてのノードの Node オブジェクト。

例:

doc = pyrs_yaml.parse("a:\n  b: 1\n  c: 2\n")
for node in doc.walk():
    print(node._path, node.root_type)
# ()       mapping
# ('a',)   mapping
# ('a', 'b') scalar
# ('a', 'c') scalar

scalars()

walk() と同様ですが、スカラー/null ノードのみを生成します。

scalars() -> Generator[Node, None, None]

生成するもの: ドキュメントツリー内のすべてのスカラーまたは null ノードの Node オブジェクト。

例:

doc = pyrs_yaml.parse("a: hello\nb: null\n")
for node in doc.scalars():
    print(node._path, node.value)
# ('a',) hello
# ('b',) None

insert()

シーケンスの指定インデックスに値を挿入します。

insert(path: str, index: int, value: Any) -> None

index はシーケンスの現在の長さまで指定できます(len への挿入は追加と同等)。負のインデックスは末尾から数えます(-1 は最後の要素の前に挿入)。パスはシーケンスノードに解決される必要があります。

スロー:

  • YamlEditError — パスがマッピングまたはスカラーに解決されるなら edit failed: not-a-sequence、 len より上か -len より下のインデックスなら edit failed: index-out-of-range-edit、解決しない パスなら edit failed: missing-path:<key>、エイリアスを経由するパスなら edit failed: cannot-edit-alias、スカラー値の下にあるパスなら edit failed: cannot-descend-into-scalar:<segment>

append()

シーケンスの末尾に値を追加します。

append(path: str, value: Any) -> None

スロー: insert() と同じ YamlEditError の理由で、シーケンスでない対象は edit failed: not-a-sequence、エイリアスの親は edit failed: cannot-edit-alias と実測しました。

delete()

パスでノードを削除します。マッピングの順序は保持されます。

delete(path: str, on_duplicate: str = "one") -> None

スロー:

  • YamlEditError — 文書が持たないキーなら edit failed: missing-path(del doc["zz"] もこれに 答えます)、シーケンスの外側のインデックスなら edit failed: index-out-of-range-edit、ノードの アンカーがまだ参照されているなら edit failed: anchor-is-referenced、on_duplicate="error" で そのキーをつづる組が二つ以上あるなら edit failed: duplicate-key-target、それ以外の on_duplicate なら edit failed: unknown on_duplicate "<value>"; expected one, all or error、エイリアスを経由する パスなら edit failed: cannot-edit-alias、delete("$") なら edit failed: edit-error—— ルートには取り除くセグメントが残っていません

rename()

マッピングキーをその場でリネームします(位置とメタデータを保持)。

rename(path: str, new_key: str) -> None

スロー:

  • YamlEditError — $ なら edit failed: cannot-rename-root、複合キーまたはシーケンス要素なら edit failed: cannot-rename-complex-key、マッピングがすでに持つ new_key なら edit failed: rename-key-exists、解決しないパスなら edit failed: missing-path、エイリアスを 経由するパスなら edit failed: cannot-edit-alias

キーをそれ自身へリネームするのは拒否ではありません:a: 1 で実測すると、rename("$.a", "a") は文書を a: 1 のまま残します。

node()

ドキュメントルートの Node を返します。

node() -> Node

find()

パスでノードを検索します。ワイルドカード([*])とディープスキャン(..)をサポート — その場合、ノードのリストを返します。

find(path: str) -> Node | list[Node]

スロー:

  • YamlPathError — パスが不正、または編集パスでワイルドカード/.. を使用
  • YamlEditError — 編集を適用できない(エイリアス経由の編集、ルート/複合キーのリネーム、スカラーへのナビゲーション、インデックス範囲外)
  • YamlTypeError — 書き手が知らない Python 型の値 — tuple はこれに当たりません(シーケンスとして書き出されます)
  • YamlDocumentError — ドキュメント編集後に陳腐化した Node を使用

参照: インプレース編集ガイド

例:

doc = pyrs_yaml.parse("items: [1, 2, 3]")
doc.set("$.items[1]", "two")
doc.insert("$.items", 1, "x")  # items: [1, x, 2, 3]
doc.append("$.items", 4)
doc.rename("$.items", "list")  # マッピングキーをリネーム
del doc["list"]  # doc.delete("$.list") と同等

ダンダー メソッド

__getitem__()

キー(マッピング)またはインデックス(シーケンス)でアクセスします。

doc = pyrs_yaml.parse("key: value")
value = doc["key"]  # 'value'

スロー:

  • KeyError — マッピングにキーが見つかりません。実測したテキストは Key 'zz' not found で、 これは組み込みの KeyError なので str(exc) は外側の引用符付きの "Key 'zz' not found" を見せます
  • IndexError — シーケンスのインデックスが範囲外。 pyrs_yaml.parse("- a\n- b\n")[99] で実測すると Index 99 out of range (len=2)
  • TypeError — キーの種類が違う場合、またはそもそも添字にできないルートの YamlTypeError 節で、それぞれ実測しました:parse("- a\n")["k"] → Index must be an integer、parse("a: 1\n")[99] → Key must be a string、 parse("just a scalar")[0] → YamlDocument is not subscriptable

上のテキストはすべて pyrs_yaml.set_language() に追従します——zh-CN の下で実測すると、 四つの節は 索引必须是整数、键必须是字符串、YamlDocument 不支持下标操作、 索引 99 超出范围(长度=2) と答えます。i18n サポート を 参照してください。

__setitem__()

ルートマッピングキーを設定します(doc.set() のルート用糖衣構文)。

doc["key"] = value

__delitem__()

ルートマッピングキーを削除します(doc.delete() のルート用糖衣構文)。

del doc["key"]

__contains__()

キーが存在するか確認します。

"key" in doc  # True

__len__()

アイテム数を取得します。

len(doc)

__iter__()

キー(マッピング)または値(シーケンス)を反復します。

for key in doc:
    print(key)

__repr__()

デバッグ表現。

repr(doc)  # "YamlDocument({key: value})"

__str__()

文字列表現。

str(doc)  # "YamlDocument({key: value})"

__eq__()

等値比較。2つの YamlDocument が同じ内容を持つ場合、true を返します。

doc1 == doc2  # True or False

使用例

import pyrs_yaml

doc = pyrs_yaml.parse("""
name: Alice
age: 30
""")

print(doc.get("name"))  # Alice
print(doc.root_type())  # mapping
print(len(doc))  # 2
print("name" in doc)  # True
for key in doc:
    print(key, doc[key])  # name Alice, age 30

自動生成の API リファレンス

以下の内容は mkdocstrings がライブラリ自身の docstring と生成された型スタブから描画するため、署名はコード由来であり書き写しではありません。

pyrs_yaml.YamlDocument

Round-trip editable YAML document with transaction support, path editing, and source preservation.

__contains__

__contains__(key)

Check if a key exists in the mapping.

__delitem__

__delitem__(key)

Delete a mapping key, del doc['key'].

__enter__

__enter__()

Enter a transaction scope: snapshot AST + splice state. with doc: exits cleanly preserving edits; exceptions roll back the snapshot.

__getitem__

__getitem__(key)

Access a child node by key (mapping) or index (sequence).

__iter__

__iter__()

Return an iterator over keys (mapping) or values (sequence).

__len__

__len__()

Return the number of mapping entries or sequence length.

__repr__

__repr__()

Return a YamlDocument(...) representation.

__setitem__

__setitem__(key, value)

Set the value for a mapping key, doc['key'] = value.

__str__

__str__()

Return the YAML string representation.

flush_source

flush_source()

Lazily re-serialize the AST into source if edits have occurred.

get

get(key, default=None)

Access a value by top-level mapping key, returning default if not found. Path-based access is available via find() / node().

reparse

reparse(
    resolve_merges=True,
    schema=None,
    honor_version_directive=None,
)

Reparse the current source, optionally changing merge behavior and schema.

honor_version_directive=None keeps the document's current negotiation setting; passing False stops honouring a declared %YAML version.

root_type

root_type()

Return the root node type: scalar/mapping/sequence/null/alias.

source

source()

Return the current YAML source string.

to_dict

to_dict()

Convert the document to a Python dict/list, resolving anchor references.

to_json

to_json(indent=2)

Serialize to a JSON string via the native engine (single AST pass).

Previously this round-tripped the AST through to_dict() + Python json.dumps — a double conversion that measured ~10x slower than the native serializer, for byte-identical output on ASCII documents. Non- ASCII is now emitted as raw UTF-8 (like to_jsonc / to_json5) rather than json.dumps' \uXXXX escapes.

Raises YamlSerializeError whose message is the stable reason key json-cannot-represent-non-finite when the document holds infinity or NaN: RFC 8259 has no literal for either, and every substitute would silently change the value (".inf" reads back as text, null is a different number). Use to_json5, which owns the token, or convert the value first.

to_json5

to_json5(indent=2)

Serialize to JSON5 text, restoring single-quoted strings, the 0x… / .5 / +7 / Infinity / NaN numeric forms and // comments as the native parser preserved them on the AST.

to_jsonc

to_jsonc(indent=2)

Serialize to JSONC text, preserving the comments the AST carries (both // line and /* */ block, emitted as //). Like to_json this routes through the native engine rather than json.dumps, so a document parsed from JSONC round-trips its notes; comments are the only thing JSONC adds over strict JSON here, and a non-finite float is refused for the same reason it is there.

to_toml

to_toml()

Serialize the document to TOML text via the native engine. Mirrors to_json: the AST is written directly, so a parsed document reaches TOML without the to_yaml()-then-re-parse round-trip that the module-level to_toml(yaml_str) helper implies. Errors when the root is not a table (TOML has no top-level scalar/array form).

to_yaml

to_yaml()

Serialize the document to a YAML string (default 2-space indent).

to_yaml_with_options

to_yaml_with_options(
    indent_size=2,
    explicit_start=False,
    explicit_end=False,
    sort_keys=False,
    max_depth=1000,
    width=80,
    indent_mapping=None,
    indent_sequence=None,
    indent_offset=None,
    note_placement="note_first",
)

Serialize with customizable indent, sorting, and explicit start/end markers.

note_placement decides where a note line goes when it cannot ride its own line and an &a / !tag header line sits directly above it: note_first (the default) writes it above that header, which is where reading the text back files it, so the first emission already settles; header_first keeps the header line on top and is not a fixed point for such a shape. Any other value is a named refusal.

validate

validate(schema)

Validate the document against a JSON Schema.

The schema is either a mapping or the JSON text of one: a str argument is parsed with json.loads, and a text that is not JSON - the YAML spelling, say - is refused with YamlValidateError instead of evaluated. Pass such a schema as a dict.

Evaluation is delegated to the third-party jsonschema package, which this distribution does not install: run pip install jsonschema before validating. If the package is absent the call raises YamlValidateError naming that install route, not a bare ModuleNotFoundError.

version

version()

Return the YAML version: the one the document's %YAML directive declared, or this reader's own version when the source declares none.

set_many

set_many(pairs)

Set multiple values at once (single splice burst).

Paths may include wildcards (``$.items[*].active``); every matching node
is set. Accepts ``{"path": value, ...}``.

sort_keys

sort_keys(path='$')

Sort the mapping keys at path (default root) in place.

A path that resolves to a scalar is a no-op, not an error: a scalar has no
keys to sort. A path that does not resolve raises ``YamlEditError``.