Skip to content

Node Class

Node Class

The Node class provides a borrowed view into a YamlDocument's AST, enabling tree traversal, query, and mutation operations. A node is created via doc.node(), doc.find("$.path"), or doc.walk().

Overview

class Node:
    """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. Nodes become stale when the document is modified or released.

Constructor

Node.__init__()

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

Parameters:

  • document — The parent YamlDocument
  • path — A tuple of path segments (keys/indexes) navigating to the target node

Properties

value

Get the scalar value of this node.

value -> Any | None

Returns None for non-scalar nodes (mappings, sequences).

Reading goes through the document's dict projection, and that is where it can refuse: KeyError for a path the document does not hold, YamlTypeError when two distinct YAML keys project to the same Python key. A projection refusal belongs to the document rather than to the path — on such a document every Node read raises it, whichever path was used. Writing does not read the projection: set_value() walks the AST, so on a colliding name it lands on the first pair the reader folds to that name.

root_type

Get the type of this node.

root_type -> str

Returns one of "scalar", "mapping", "sequence", "null".

An alias node reports its target's type, never a spelling of its own: measured on defaults: &d\n timeout: 30\nprod: *d\n and src: &s\n - a\nref: *s\n, the nodes at $.prod and $.ref answer "mapping" and "sequence", and the scalar alias at $.use in base: &x 1\nuse: *x\n answers "scalar".

_path

The path tuple that navigates to this node within the document's AST.

_path -> tuple

path

Get this node's path segments (tuple of keys and indices). Unlike _path, this is the documented public accessor — useful for logging, error messages, and re-finding a node after it becomes stale.

path -> tuple

children

Get the child nodes of this node.

children -> list[Node]

Returns an empty list for scalar/null nodes.

parent

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

parent -> Node | None

comment

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

comment -> str | None

anchor

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

anchor -> str | None

tag

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

tag -> str | None

scalar_style

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

scalar_style -> str | None

flow_style

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

flow_style -> bool | None

chomping

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

chomping -> str | None

Methods

find()

Find a node by JSONPath-like path.

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

Supported path syntax:

Pattern Description
$.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
$..* All descendant nodes

Returns: A single Node for exact paths, or a list[Node] for wildcard/deep-scan queries.

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 all descendant nodes (depth-first pre-order).

walk() -> Iterator[Node]

Yields: The node itself, then all descendants recursively.

filter()

Filter descendant nodes by a predicate function.

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

Parameters:

  • predicate — A function taking a Node and returning bool

Example:

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

set_value()

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

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

With create_missing=True, missing intermediate mapping keys along the path are created as nested mappings. Index segments that miss are still an error.

Measured edges:

  • A node find() could not resolve — the Node(invalid) object — still writes: doc.node().find("$.zz").set_value(3) adds zz: 3. Reading its value is the refusal (KeyError), not the write
  • On an alias node the call is not a refusal either — it rewrites the alias in place: parse("base: &x 1\nuse: *x\n").node().find("$.use").set_value(42) emits base: &x 1\nuse: 42\n
  • Writing through an alias is refused: edit failed: cannot-edit-alias
  • On a stale node it emits a RuntimeWarning and raises YamlDocumentError: document has been modified; re-find the node
  • A Python value the writer does not know is a YamlTypeError (Unsupported Python type for YAML conversion), not an edit error

append()

Append a value to a sequence node.

append(value: Any) -> None

insert()

Insert into a sequence node at an index.

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

delete()

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

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

Measured refusals: the root node answers YamlEditError: edit failed: edit-error, a node whose anchor an alias still references answers edit failed: anchor-is-referenced, and on_duplicate="error" on a document where two pairs spell the key answers edit failed: duplicate-key-target. Deleting an alias pair is not a refusal — find("$.prod").delete() on defaults: &d\n timeout: 30\nprod: *d\n leaves defaults: &d\n timeout: 30\n. The stale node answers YamlDocumentError on the next access but is_valid() still answers True.

rename()

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

rename(new_key: str) -> None

Measured refusals: the root answers YamlEditError: edit failed: cannot-rename-root, a sequence element — which has no key — answers edit failed: cannot-rename-complex-key, a new_key the mapping already holds answers edit failed: rename-key-exists, and a node whose key is a complex node never reaches the engine: parse("? [1, 2]\n: value\n").node().children[0].rename("b") answers YamlEditError: ValueError: segment must be str or int. Renaming to the same key is a no-op, and on an alias pair the call renames the key rather than refusing — find("$.prod").rename("prod2") on defaults: &d\n timeout: 30\nprod: *d\n leaves defaults: &d\n timeout: 30\nprod2: *d\n.

set_comment()

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.

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

remove_comment()

Remove this node's comment.

remove_comment() -> None

set_anchor()

Set (or replace) this node's anchor.

set_anchor(name: str) -> None

Refused with YamlEditError: edit failed: anchor-is-referenced while an alias still points at the current anchor — measured on base: &x 1\nuse: *x\n, where find("$.base").set_anchor("renamed") fails and, with the alias gone, the same call on base: &x 1\n emits base: &renamed 1. On an alias node itself it answers edit failed: cannot-edit-alias.

remove_anchor()

Remove this node's anchor.

remove_anchor() -> None

Same guard as set_anchor(): measured on base: &x 1\nuse: *x\n, find("$.base").remove_anchor() answers YamlEditError: edit failed: anchor-is-referenced.

set_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.

set_tag(tag: str) -> None

remove_tag()

Remove this node's YAML tag.

remove_tag() -> None

set_scalar_style()

Set (or replace) this node's scalar style. No-op on non-scalar nodes. Recognized values: "plain", "single_quoted", "double_quoted", "literal", "folded".

set_scalar_style(style: str) -> None

set_flow_style()

Set (or replace) this node's flow style. True emits flow ({}/[]), False emits block. No-op on non-container nodes.

set_flow_style(flow: bool) -> None

set_chomping()

Set (or replace) this node's chomping indicator. Recognized values: "strip" (-), "clip" (default), "keep" (+). No-op on non-scalar nodes.

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

Measured edges: a destination whose parent exists need not exist itself — find("$.src").move("$.nope") on src:\n x: 1\n leaves nope:\n x: 1\n — while a destination with a missing intermediate answers YamlEditError: edit failed: missing-path:deep. Replacing a scalar destination works: dst: 2 becomes dst:\n x: 1\n. Moving the root answers edit failed: edit-error, moving a subtree onto its own path empties the document (find("$.src").move("$.src") leaves {}\n), and a destination whose value still carries a referencing alias answers edit failed: anchor-is-referenced.

to_yaml()

Serialize this subtree to a YAML string.

to_yaml() -> str

copy()

Deep-copy this subtree as a standalone Python value (dict/list/scalar), detached from the document. Useful for duplicating a subtree to paste elsewhere via set_value().

copy() -> Any

is_valid()

Check if the parent document is still alive.

is_valid() -> bool

This answers a question about the document, not about the path. A node whose path resolves to nothing — an absent key, a name two YAML keys share, or one made stale by a later edit — is still valid, so is_valid() is not a way to test whether value will answer. __repr__ carries that signal instead.

release()

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

release() -> None

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

Dunder Methods

__repr__()

__repr__() -> str

Returns Node(root_type=<type>, path=<path>) when the path resolves, Node(released) once release() has run, or Node(invalid) when the path does not resolve — because the document was modified, because it names nothing the document holds, or because the projection refuses (see value).

__eq__()

__eq__(other: object) -> bool

Two Node instances are equal if they share the same document, path, and alive state.

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

Stale Node Behavior

Stale nodes

A Node is tied to the document's revision at creation time. Any document edit bumps the revision, so previously obtained nodes become stale. Always re-find a node after editing the document.

A node becomes stale when:

  • The parent YamlDocument is garbage collected
  • release() is called explicitly
  • The document is modified after the node was created

Accessing a stale node emits a RuntimeWarning and raises YamlDocumentError:

Stale node example
>>> 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. Accessing a stale node triggers a RuntimeWarning first.
  2. Then raises YamlDocumentError. Re-acquire the node via doc.node().find(path).

Example

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

Generated API reference

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

pyrs_yaml.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