コンテンツにスキップ

Node クラス

Node クラス

Node クラスは、YamlDocument の AST への借用ビューを提供し、ツリーの走査、クエリ、および変更操作を可能にします。ノードは doc.node()、doc.find("$.path")、または doc.walk() で作成されます。

概要

class Node:
    """A node in the YAML AST, backed by a YamlDocument and a path."""

各 Node は、親 YamlDocument への参照と、ドキュメントの AST 内のターゲットノードに移動するパス タプルを保持します。ノードは、ドキュメントが変更または解放されると期限切れになります。

コンストラクタ

Node.__init__()

Node.__init__(document: YamlDocument, path: tuple = ()) -> None

Parameters:

  • document — 親 YamlDocument
  • path — ターゲットノードに移動するパスセグメント(キー/インデックス)のタプル

プロパティ

value

このノードのスカラー値を取得します。

value -> Any | None

非スカラーノード(マッピング、シーケンス)の場合は None を返します。

取得に失敗すると例外が出ます。パスが存在しなければ KeyError、異なる二つの YAML キーが 同じ Python キーに畳まれる場合は YamlTypeError です(to_dict() が同じ地点で拒否します)。 後者の拒否はパスではなくドキュメントに属する性質なので、そのようなドキュメントではどのパス でも Node の取得が例外を投げます。書き込みはこの取得を通りません。set_value() は AST を 直接たどるため、名前が重なるときはその名前に畳まれる最初のペアに反映されます。

root_type

このノードの型を取得します。

root_type -> str

"scalar"、"mapping"、"sequence"、"null" のいずれかを返します。

エイリアスノードは参照先の型を報告し、自分専用の型名を決して返しません: defaults: &d\n timeout: 30\nprod: *d\n と src: &s\n - a\nref: *s\n で実測すると、 $.prod と $.ref のノードは "mapping" と "sequence" と答え、base: &x 1\nuse: *x\n の $.use にあるスカラーのエイリアスは "scalar" と答えます。

_path

このノードをドキュメントの AST 内に位置付けるパス タプルです。

_path -> tuple

path

Get this node's path segments (tuple of keys and indices). The public accessor for logging, error messages, and re-finding a node after it becomes stale.

path -> tuple

children

このノードの子ノードを取得します。

children -> list[Node]

スカラー/Null ノードの場合は空のリストを返します。

parent

親 Node を取得します。ルートの場合は None を返します。

parent -> Node | None

comment

このノードのコメントテキストを取得します。コメントがない場合は None を返します。

comment -> str | None

anchor

このノードのアンカー名を取得します。アンカーがない場合は None を返します。

anchor -> str | None

tag

このノードの YAML タグ文字列(例: !!str)を取得します。タグがない場合は None を返します。

tag -> str | None

scalar_style

スカラー style を取得します("plain"、"single_quoted"、"double_quoted"、"literal"、"folded")。非スカラーノードは None を返します。

scalar_style -> str | None

flow_style

flow style を取得します(True = flow {}/[]、False = block)。非コンテナノードは None を返します。

flow_style -> bool | None

chomping

chomping 指示子を取得します("strip"、"clip"、"keep")。非スカラーノードは None を返します。

chomping -> str | None

メソッド

find()

JSONPath ライクなパスでノードを検索します。

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

対応するパス構文:

Pattern Description
$.key ルートキー
$.key.subkey ネストされたキー
$.arr[0] シーケンスへのインデックス
$.arr[*] シーケンス内のすべてのアイテム
$..key 任意の深さでキーを検索
$..* すべての子孫ノード

戻り値: 厳密なパスには単一の Node、ワイルドカード/深層検索クエリには list[Node]。

find_first()

Find the first matching node by JSONPath-like path. Always returns a single Node or None (never a list) — for wildcard paths ([*]), returns the first element.

find_first(path: str) -> Node | None

walk()

すべての子孫ノードを走査します(深さ優先の先行順)。

walk() -> Iterator[Node]

生成: ノード自体、次にすべての子孫を再帰的に生成します。

filter()

述語関数で子孫ノードをフィルタリングします。

filter(predicate: Callable[[Node], bool]) -> list[Node]

Parameters:

  • predicate — Node を受け取り bool を返す関数

Example:

scalars = root.filter(lambda n: n.root_type == "scalar")

set_value()

このノードの値を置き換え、メタデータ(コメント、アンカー、タグ、スタイル)を保持します。

set_value(value: Any, create_missing: bool = False) -> None

create_missing=True の場合、パスに沿った欠落している中間マッピングキーがネストされたマッピングとして作成されます。インデックスセグメントが欠落している場合は引き続きエラーになります。

実測した境界:

  • find() が解決できなかったノード——Node(invalid) のオブジェクト——も引き続き書き込みます: doc.node().find("$.zz").set_value(3) は zz: 3 を追加します。拒否されるのは書き込みではなく、 その value を読むことです(KeyError)
  • エイリアスノードでもこの呼び出しは拒否ではなく、エイリアスをその場で書き換えます: parse("base: &x 1\nuse: *x\n").node().find("$.use").set_value(42) は base: &x 1\nuse: 42\n を出力します
  • エイリアス経由の書き込みは拒否されます:edit failed: cannot-edit-alias
  • 期限切れノードでは RuntimeWarning を発行し、 YamlDocumentError: document has been modified; re-find the node を発生させます
  • 書き手が知らない Python の値は編集エラーではなく YamlTypeError (Unsupported Python type for YAML conversion)です

append()

シーケンスノードに値を追加します。

append(value: Any) -> None

insert()

シーケンスノードのインデックスに挿入します。

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

delete()

このノードとそのコメントを削除します。その後、ノードは期限切れになります。

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

実測した拒否:ルートノードは YamlEditError: edit failed: edit-error、そのアンカーを エイリアスがいまだ参照しているノードは edit failed: anchor-is-referenced、二つの組が 同じキーをつづる文書での on_duplicate="error" は edit failed: duplicate-key-target と 答えます。エイリアスの組の削除は拒否ではありません—— defaults: &d\n timeout: 30\nprod: *d\n で find("$.prod").delete() は defaults: &d\n timeout: 30\n を残します。期限切れのノードは次のアクセスで YamlDocumentError と答えますが、is_valid() は依然として True と答えます。

rename()

このノードのマッピングキーの名前を変更します。ノードはマッピングの値である必要があります。

rename(new_key: str) -> None

実測した拒否:ルートは YamlEditError: edit failed: cannot-rename-root、キーを持たない シーケンス要素は edit failed: cannot-rename-complex-key、マッピングがすでに持つ new_key は edit failed: rename-key-exists と答えます。キーが複合ノードであるノードはエンジンにすら 届きません:parse("? [1, 2]\n: value\n").node().children[0].rename("b") は YamlEditError: ValueError: segment must be str or int と答えます。同じキーへのリネームは no-op で、エイリアスの組ではこの呼び出しは拒否せずキーをリネームします—— defaults: &d\n timeout: 30\nprod: *d\n で find("$.prod").rename("prod2") は defaults: &d\n timeout: 30\nprod2: *d\n を残します。

set_comment()

このノードのコメントを設定(または置換)します。standalone=True(デフォルト)ではコメントがノードの上の独立した行に出力され、standalone=False ではノードの後ろにインラインで出力されます。

set_comment(text: str, standalone: bool = True) -> None

remove_comment()

このノードのコメントを削除します。

remove_comment() -> None

set_anchor()

このノードのアンカーを設定(または置換)します。

set_anchor(name: str) -> None

現在のアンカーをエイリアスがいまだ指しているあいだは YamlEditError: edit failed: anchor-is-referenced で拒否されます——base: &x 1\nuse: *x\n で 実測すると find("$.base").set_anchor("renamed") は失敗し、エイリアスを無くせば同じ呼び出しは base: &x 1\n に対して base: &renamed 1 を出力します。エイリアスノード自身では edit failed: cannot-edit-alias と答えます。

remove_anchor()

このノードのアンカーを削除します。

remove_anchor() -> None

set_anchor() と同じガードです:base: &x 1\nuse: *x\n で実測すると、 find("$.base").remove_anchor() は YamlEditError: edit failed: anchor-is-referenced と答えます。

set_tag()

このノードの YAML タグを設定(または置換)します。"!custom" はローカルタグ、"!!int" はプライマリ(!!)タグ、"!<tag:yaml.org,2002:str>" はバーベイタムタグになります。

set_tag(tag: str) -> None

remove_tag()

このノードの YAML タグを削除します。

remove_tag() -> None

set_scalar_style()

スカラー style を設定(または置換)します。非スカラーノードでは no-op。値: "plain", "single_quoted", "double_quoted", "literal", "folded"。

set_scalar_style(style: str) -> None

set_flow_style()

flow style を設定(または置換)します。True は flow({}/[])、False は block。非コンテナノードでは no-op。

set_flow_style(flow: bool) -> None

set_chomping()

chomping 指示子を設定(または置換)します。値: "strip"(-), "clip"(デフォルト), "keep"(+)。非スカラーノードでは no-op。

set_chomping(chomp: str) -> None

sort_keys()

Sort the keys of this mapping node in place. No-op on non-mapping nodes.

sort_keys() -> None

move()

Move this subtree to a new path in the same document (copies the subtree to new_path, then removes the source). new_path is an absolute JSONPath.

move(new_path: str) -> None

実測した境界:行き先そのものは存在しなくても、その親が存在していればよい—— src:\n x: 1\n で find("$.src").move("$.nope") は nope:\n x: 1\n を残します——一方で、 中間キーが欠けた行き先は YamlEditError: edit failed: missing-path:deep と答えます。スカラーの 行き先を置き換えるのは動きます:dst: 2 は dst:\n x: 1\n になります。ルートの移動は edit failed: edit-error、部分木を自分のパスへ移すのは文書を空にし( find("$.src").move("$.src") は {}\n を残します)、参照中のエイリアスをまだ値に持つ行き先は edit failed: anchor-is-referenced と答えます。

to_yaml()

このサブツリーを YAML 文字列にシリアライズします。

to_yaml() -> str

copy()

このサブツリーをドキュメントから切り離された独立した Python 値(dict/list/scalar)として深くコピーします。set_value() で別の場所に貼り付ける際などに使えます。

copy() -> Any

is_valid()

親ドキュメントがまだ有効かどうかを確認します。

is_valid() -> bool

これはドキュメントについての問いであり、パスについての問いではありません。パスが 何も解決できないノード(キーが存在しない、二つの YAML キーが同じ Python 名に畳まれる、 後続の編集でノードが期限切れになった)も依然として有効なので、is_valid() で value が応答するかどうかは判定できません。その信号は __repr__ が伝えます。

release()

親ドキュメントへの参照を解放し、このノードを期限切れとしてマークします。

release() -> None

release() を呼び出した後、このノードへのアクセスは RuntimeWarning を発行し、YamlDocumentError を発生させます。

ダンダーメソッド

__repr__()

__repr__() -> str

パスが解決できる場合は Node(root_type=<type>, path=<path>)、release() を呼び出した 後は Node(released)、解決できない場合は Node(invalid) を返します。後者は、ドキュメントが 変更されたか、パスが何も指していないか、値の取得が拒否された(value を参照)場合に現れます。

__eq__()

__eq__(other: object) -> bool

2 つの Node インスタンスは、同じドキュメント、パス、および有効状態を共有する場合に等しいとみなされます。

value_eq()

Compare this node's resolved value with another node or Python value. Unlike __eq__ (reference identity), this compares the actual YAML value.

value_eq(other: object) -> bool

無効なノードの動作

期限切れノード

Node はドキュメントのリビジョンに結び付けられています。ドキュメントが編集されるとリビジョンが増加し、以前に取得したノードは期限切れになり、YamlDocumentError をスローします。編集後はノードを再取得してください。

ノードは次の場合に期限切れになります:

  • 親 YamlDocument がガベージコレクションされた
  • release() が明示的に呼び出された
  • ノード作成後にドキュメントが変更された

期限切れのノードにアクセスすると、RuntimeWarning が発行され、YamlDocumentError が発生します:

期限切れノードの例
>>> node = doc.node()
>>> doc.set("$.key", "new_value")
>>> node.value  # (1)!
RuntimeWarning: Node is stale: the document was modified after this node was created
YamlDocumentError: document has been modified; re-find the node  # (2)!
  1. 期限切れのノードにアクセスすると、最初に RuntimeWarning がトリガーされます。
  2. 次に YamlDocumentError が発生します。doc.node().find(path) でノードを再取得してください。

例

import pyrs_yaml

doc = pyrs_yaml.parse("""
a:
  b: 1
  c: [2, 3, 4]
d: hello
""")

# Get root node
root = doc.node()
print(root.root_type)  # "mapping"

# Navigate
node = root.find("$.a.c[1]")
print(node.value)  # 3

# Walk
for n in root.walk():
    print(n._path, n.root_type)

# Filter
numbers = root.filter(lambda n: n.root_type == "scalar" and isinstance(n.value, int))
for n in numbers:
    print(n._path, n.value)  # ('a', 'b') 1, ('a', 'c', 0) 2, ...

# Mutate
root.find("$.a.b").set_value(42)
root.find("$.a.c").append(5)
root.find("$.d").rename("greeting")
root.find("$.a.c[0]").delete()

print(doc.to_yaml())
# a:
#   b: 42
#   c: [3, 4, 5]
# greeting: hello

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

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

pyrs_yaml.Node

Node(document, path=())

A node in the YAML AST, backed by a YamlDocument and a path.

Each Node stores a reference to its parent YamlDocument and a path tuple that navigates to the target node within the document's AST.

Source code in python/pyrs_yaml/node.py
33
34
35
36
37
def __init__(self, document: Any, path: tuple[Any, ...] = ()) -> None:
    self._doc = document
    self._path = path
    self._alive = True
    self._revision_at_creation = document._revision() if document is not None else 0

path property

path

Get this node's path segments (tuple of keys and indices).

The path can be used to reconstruct a JSONPath-like string or to re-find the node after it becomes stale.

root_type property

root_type

Get the type of this node: scalar, mapping, sequence, null, alias.

value property

value

Get the scalar value of this node.

Returns None for container nodes (mappings and sequences). Use the following alternatives for containers:

  • node.children — iterate over child nodes
  • node.to_yaml() — serialize the subtree to a YAML string
  • doc.get(key) — access a value by literal mapping key from the document

comment property

comment

Get this node's comment text, or None if it has no comment.

leading_comment property

leading_comment

Get this node's leading (standalone) comment text.

Returns the note the source carried on its own line above the node. For YAML documents the receiver historically stored standalone notes on the comment slot with a standalone flag; the getter normalises across both representations, so a parsed YAML document and a parsed TOML / JSONC document both surface their leading note here.

None when the node has no standalone comment.

leading_comments property

leading_comments

Every leading (standalone) note above this node, in source order.

A document may stack any number of comment lines directly above one key; all of them are preserved. :attr:leading_comment returns only the first, and is unchanged for documents that carry a single note.

An empty list when the node has no standalone comment.

anchor property

anchor

Get this node's anchor name, or None if it has no anchor.

tag property

tag

Get this node's YAML tag string (e.g. !!str), or None.

scalar_style property

scalar_style

Get the scalar style ("plain", "single_quoted", "double_quoted", "literal", "folded"), or None for non-scalar nodes.

flow_style property

flow_style

Get the flow style (True = flow {}/[], False = block), or None for non-container nodes.

chomping property

chomping

Get the chomping indicator ("strip", "clip", "keep"), or None for non-scalar nodes.

parent property

parent

Get the parent Node, or None if this is the root.

children property

children

Get the child nodes of this node.

is_valid

is_valid()

Check if the parent document is still alive.

Source code in python/pyrs_yaml/node.py
67
68
69
def is_valid(self) -> bool:
    """Check if the parent document is still alive."""
    return self._alive and self._doc is not None

release

release()

Release the reference to the parent document, marking this node as stale.

After calling release(), any access to this node will emit a RuntimeWarning and raise YamlDocumentError.

Source code in python/pyrs_yaml/node.py
80
81
82
83
84
85
86
87
def release(self) -> None:
    """Release the reference to the parent document, marking this node as stale.

    After calling release(), any access to this node will emit a RuntimeWarning
    and raise YamlDocumentError.
    """
    self._alive = False
    self._doc = None

to_yaml

to_yaml()

Serialize this subtree to YAML string.

Source code in python/pyrs_yaml/node.py
116
117
118
119
120
121
122
123
124
125
126
127
def to_yaml(self) -> str:
    """Serialize this subtree to YAML string."""
    resolved = self._resolve()
    if isinstance(resolved, (dict, list)):
        from pyrs_yaml import from_dict

        return from_dict(resolved)
    if resolved is None:
        return "null\n"
    if isinstance(resolved, str):
        return resolved + "\n"
    return str(resolved) + "\n"

copy

copy()

Deep-copy this subtree as a standalone value (dict/list/scalar).

The result is detached from the document — useful for duplicating a subtree to paste elsewhere via set_value().

Source code in python/pyrs_yaml/node.py
129
130
131
132
133
134
135
136
def copy(self) -> Any:
    """Deep-copy this subtree as a standalone value (dict/list/scalar).

    The result is detached from the document — useful for duplicating a
    subtree to paste elsewhere via ``set_value()``.
    """
    doc = self._get_doc()
    return doc._copy_path([s for s in self._path])

set_value

set_value(value, create_missing=False)

Replace this node's value, preserving its metadata (comment/anchor/tag/style).

With create_missing=True, missing intermediate mapping keys along the path are created as nested mappings (e.g. setting a.b.c on a: 1 creates b and c). Index segments that miss are still an error.

Source code in python/pyrs_yaml/node.py
138
139
140
141
142
143
144
145
146
def set_value(self, value: Any, create_missing: bool = False) -> None:
    """Replace this node's value, preserving its metadata (comment/anchor/tag/style).

    With ``create_missing=True``, missing intermediate mapping keys along
    the path are created as nested mappings (e.g. setting ``a.b.c`` on
    ``a: 1`` creates ``b`` and ``c``). Index segments that miss are still
    an error.
    """
    self._with_path(lambda doc, segs: doc._set_path(segs, value, create_missing))

append

append(value)

Append to a sequence node.

Source code in python/pyrs_yaml/node.py
148
149
150
def append(self, value: Any) -> None:
    """Append to a sequence node."""
    self._with_path(lambda doc, segs: doc._append_path(segs, value))

insert

insert(index, value)

Insert into a sequence node at index.

Source code in python/pyrs_yaml/node.py
152
153
154
def insert(self, index: int, value: Any) -> None:
    """Insert into a sequence node at index."""
    self._with_path(lambda doc, segs: doc._insert_path(segs, index, value))

delete

delete(on_duplicate='one')

Remove this node and its comments. Node becomes stale afterwards.

on_duplicate decides what a delete means when the document holds more than one pair spelling this key, told apart only by the tag or anchor the reader keeps: "one" (the default) removes the pair the path resolves to, "all" removes every pair that key could answer with, and "error" refuses while both remain.

Source code in python/pyrs_yaml/node.py
156
157
158
159
160
161
162
163
164
def delete(self, on_duplicate: str = "one") -> None:
    """Remove this node and its comments. Node becomes stale afterwards.

    ``on_duplicate`` decides what a delete means when the document holds more than one
    pair spelling this key, told apart only by the tag or anchor the reader keeps:
    ``"one"`` (the default) removes the pair the path resolves to, ``"all"`` removes
    every pair that key could answer with, and ``"error"`` refuses while both remain.
    """
    self._with_path(lambda doc, segs: doc._delete_path(segs, on_duplicate))

rename

rename(new_key)

Rename this node's mapping key. Node must be a mapping value.

Source code in python/pyrs_yaml/node.py
166
167
168
def rename(self, new_key: str) -> None:
    """Rename this node's mapping key. Node must be a mapping value."""
    self._with_path(lambda doc, segs: doc._rename_path(segs, new_key))

set_comment

set_comment(text, standalone=True)

Set (or replace) this node's comment.

With standalone=True (default) the comment is emitted on its own line above the node; with standalone=False it is emitted inline after the node.

Source code in python/pyrs_yaml/node.py
176
177
178
179
180
181
182
183
def set_comment(self, text: str, standalone: bool = True) -> None:
    """Set (or replace) this node's comment.

    With ``standalone=True`` (default) the comment is emitted on its own
    line above the node; with ``standalone=False`` it is emitted inline
    after the node.
    """
    self._with_path(lambda doc, segs: doc._set_comment_path(segs, text, standalone))

remove_comment

remove_comment()

Remove this node's comment.

Source code in python/pyrs_yaml/node.py
185
186
187
def remove_comment(self) -> None:
    """Remove this node's comment."""
    self._with_path(lambda doc, segs: doc._remove_comment_path(segs))

set_leading_comment

set_leading_comment(text)

Set (or replace) this node's leading (standalone) comment.

Writes to the dedicated leading_comment slot introduced in PR #114 and clears any legacy standalone=True note still living on the comment slot so the two representations never disagree.

Source code in python/pyrs_yaml/node.py
218
219
220
221
222
223
224
225
226
def set_leading_comment(self, text: str) -> None:
    """Set (or replace) this node's leading (standalone) comment.

    Writes to the dedicated ``leading_comment`` slot introduced in
    PR #114 and clears any legacy ``standalone=True`` note still
    living on the ``comment`` slot so the two representations never
    disagree.
    """
    self._with_path(lambda doc, segs: doc._set_leading_comment_path(segs, text))

remove_leading_comment

remove_leading_comment()

Remove this node's leading (standalone) comment.

Clears both the leading_comment slot and any legacy comment(standalone=True) note on the same node. The inline trailing note on the comment slot is preserved.

Source code in python/pyrs_yaml/node.py
228
229
230
231
232
233
234
235
def remove_leading_comment(self) -> None:
    """Remove this node's leading (standalone) comment.

    Clears both the ``leading_comment`` slot and any legacy
    ``comment(standalone=True)`` note on the same node. The inline
    trailing note on the ``comment`` slot is preserved.
    """
    self._with_path(lambda doc, segs: doc._remove_leading_comment_path(segs))

set_anchor

set_anchor(name)

Set (or replace) this node's anchor.

Source code in python/pyrs_yaml/node.py
243
244
245
def set_anchor(self, name: str) -> None:
    """Set (or replace) this node's anchor."""
    self._with_path(lambda doc, segs: doc._set_anchor_path(segs, name))

remove_anchor

remove_anchor()

Remove this node's anchor.

Source code in python/pyrs_yaml/node.py
247
248
249
def remove_anchor(self) -> None:
    """Remove this node's anchor."""
    self._with_path(lambda doc, segs: doc._remove_anchor_path(segs))

set_tag

set_tag(tag)

Set (or replace) this node's YAML tag.

"!custom" produces a local tag, "!!int" produces a primary (!!) tag, and "!<tag:yaml.org,2002:str>" produces a verbatim tag.

Source code in python/pyrs_yaml/node.py
257
258
259
260
261
262
263
264
def set_tag(self, tag: str) -> None:
    """Set (or replace) this node's YAML tag.

    ``"!custom"`` produces a local tag, ``"!!int"`` produces a primary
    (``!!``) tag, and ``"!<tag:yaml.org,2002:str>"`` produces a verbatim
    tag.
    """
    self._with_path(lambda doc, segs: doc._set_tag_path(segs, tag))

remove_tag

remove_tag()

Remove this node's YAML tag.

Source code in python/pyrs_yaml/node.py
266
267
268
def remove_tag(self) -> None:
    """Remove this node's YAML tag."""
    self._with_path(lambda doc, segs: doc._remove_tag_path(segs))

set_scalar_style

set_scalar_style(style)

Set (or replace) this node's scalar style.

No-op on non-scalar nodes. Recognized values: "plain", "single_quoted", "double_quoted", "literal", "folded".

Source code in python/pyrs_yaml/node.py
279
280
281
282
283
284
285
def set_scalar_style(self, style: str) -> None:
    """Set (or replace) this node's scalar style.

    No-op on non-scalar nodes. Recognized values: ``"plain"``,
    ``"single_quoted"``, ``"double_quoted"``, ``"literal"``, ``"folded"``.
    """
    self._with_path(lambda doc, segs: doc._set_scalar_style_path(segs, style))

set_flow_style

set_flow_style(flow)

Set (or replace) this node's flow style.

True emits flow ({}/[]), False emits block. No-op on non-container nodes.

Source code in python/pyrs_yaml/node.py
295
296
297
298
299
300
301
def set_flow_style(self, flow: bool) -> None:
    """Set (or replace) this node's flow style.

    ``True`` emits flow (``{}``/``[]``), ``False`` emits block. No-op on
    non-container nodes.
    """
    self._with_path(lambda doc, segs: doc._set_flow_style_path(segs, flow))

set_chomping

set_chomping(chomp)

Set (or replace) this node's chomping indicator.

Recognized values: "strip" (-), "clip" (default), "keep" (+). No-op on non-scalar nodes.

Source code in python/pyrs_yaml/node.py
311
312
313
314
315
316
317
def set_chomping(self, chomp: str) -> None:
    """Set (or replace) this node's chomping indicator.

    Recognized values: ``"strip"`` (``-``), ``"clip"`` (default),
    ``"keep"`` (``+``). No-op on non-scalar nodes.
    """
    self._with_path(lambda doc, segs: doc._set_chomping_path(segs, chomp))

sort_keys

sort_keys()

Sort the keys of this mapping node in place.

Only meaningful on mapping nodes; no-op on other node types.

Source code in python/pyrs_yaml/node.py
319
320
321
322
323
324
def sort_keys(self) -> None:
    """Sort the keys of this mapping node in place.

    Only meaningful on mapping nodes; no-op on other node types.
    """
    self._with_path(lambda doc, segs: doc._sort_keys_path(segs))

move

move(new_path)

Move this subtree to a new path in the same document.

new_path is an absolute JSONPath ($.dest.key). The source node is removed after the subtree is copied to the destination.

Source code in python/pyrs_yaml/node.py
326
327
328
329
330
331
332
333
334
335
def move(self, new_path: str) -> None:
    """Move this subtree to a new path in the same document.

    ``new_path`` is an absolute JSONPath (``$.dest.key``). The source node
    is removed after the subtree is copied to the destination.
    """
    doc = self._get_doc()
    dst = Node(doc).find(new_path) if new_path != "$" else Node(doc)
    dst_segs = [s for s in dst._path]
    doc._move_path([s for s in self._path], dst_segs)

walk

walk()

Walk all descendant nodes (depth-first pre-order).

Source code in python/pyrs_yaml/node.py
359
360
361
362
363
def walk(self) -> Iterator[Node]:
    """Walk all descendant nodes (depth-first pre-order)."""
    yield self
    for child in self.children:
        yield from child.walk()

filter

filter(predicate)

Filter descendant nodes by a predicate function.

Source code in python/pyrs_yaml/node.py
365
366
367
def filter(self, predicate: Callable[[Node], bool]) -> list[Node]:
    """Filter descendant nodes by a predicate function."""
    return [node for node in self.walk() if predicate(node)]

find

find(path)

Find a node by JSONPath-like path.

The path must start with $ (a leading $ is required; a bare a.b or arr[0] raises ValueError). This is the canonical path syntax for the Python API; the Rust backend's internal path parser accepts an optional $ for compatibility.

Supports

$.key - Root key $.key.subkey - Nested key $.arr[0] - Index into sequence $.arr[*] - All items in sequence $..key - Deep search for key at any depth

Source code in python/pyrs_yaml/node.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
def find(self, path: str) -> Any:
    """Find a node by JSONPath-like path.

    The path **must** start with ``$`` (a leading ``$`` is required; a bare
    ``a.b`` or ``arr[0]`` raises ``ValueError``). This is the canonical
    path syntax for the Python API; the Rust backend's internal path parser
    accepts an optional ``$`` for compatibility.

    Supports:
        $.key           - Root key
        $.key.subkey    - Nested key
        $.arr[0]        - Index into sequence
        $.arr[*]        - All items in sequence
        $..key          - Deep search for key at any depth
    """
    segments = _parse_jsonpath(path)
    current = self
    for seg in segments:
        if isinstance(seg, int):
            doc = current._get_doc()
            idx_path = (*current._path, seg)
            current = Node(doc, idx_path)
        elif seg == "*":
            children = current.children
            return [Node(current._get_doc(), child._path) for child in children]
        elif isinstance(seg, str) and seg.startswith(".."):
            doc = current._get_doc()
            key = seg[2:]
            entries = _walk_node_paths(current._path, doc.to_dict())
            if key == "*":
                return [Node(doc, path) for path, _ in entries]
            return [Node(doc, (*path, key)) for path, value in entries if isinstance(value, dict) and key in value]
        elif isinstance(seg, str):
            doc = current._get_doc()
            val_path = (*current._path, seg)
            current = Node(doc, val_path)
    return current

find_first

find_first(path)

Find the first matching node by JSONPath-like path.

Unlike find(), this always returns a single Node or None (never a list). For wildcard paths ([*]), returns the first element.

Source code in python/pyrs_yaml/node.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def find_first(self, path: str) -> Node | None:
    """Find the first matching node by JSONPath-like path.

    Unlike ``find()``, this always returns a single ``Node`` or ``None``
    (never a list). For wildcard paths (``[*]``), returns the first element.
    """
    result = self.find(path)
    if isinstance(result, list):
        return result[0] if result else None
    try:
        result._resolve()
    except (KeyError, IndexError, TypeError, ValueError):
        return None
    return result

value_eq

value_eq(other)

Compare this node's resolved value with another node or Python value.

Unlike == (which compares reference identity), this compares the actual YAML value (dict/list/scalar/None) after resolution.

Source code in python/pyrs_yaml/node.py
437
438
439
440
441
442
443
444
445
def value_eq(self, other: object) -> bool:
    """Compare this node's resolved value with another node or Python value.

    Unlike ``==`` (which compares reference identity), this compares the
    actual YAML value (dict/list/scalar/None) after resolution.
    """
    if isinstance(other, Node):
        return self._resolve() == other._resolve()
    return self._resolve() == other