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— 父YamlDocumentpath— 定位到目标节点的路径段(键/索引)元组
属性¶
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]
对于标量/空节点返回空列表。
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 | 描述 |
|---|---|
$.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。重命名为同一个键是空操作,而在别名那一对上,这次调用重命名的是键而不是给出拒绝 — 在 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>" 生成 verbatim 标签。
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
两个 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 与文档的修订号绑定,文档编辑后之前获取的 Node 会过期。每次编辑后重新查找节点以继续工作。
节点在以下情况下过期:
- 父
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)!
- 访问过期节点会先触发
RuntimeWarning。 - 然后抛出
YamlDocumentError。请通过doc.node().find(path)重新获取节点。
示例¶
import pyrs_yaml
doc = pyrs_yaml.parse("""
a:
b: 1
c: [2, 3, 4]
d: hello
""")
# 获取根节点
root = doc.node()
print(root.root_type) # "mapping"
# 导航
node = root.find("$.a.c[1]")
print(node.value) # 3
# 遍历
for n in root.walk():
print(n._path, n.root_type)
# 过滤
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, ...
# 修改
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 | |
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.
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 nodesnode.to_yaml()— serialize the subtree to a YAML stringdoc.get(key)— access a value by literal mapping key from the document
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.
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.
is_valid
¶
is_valid()
Check if the parent document is still alive.
Source code in python/pyrs_yaml/node.py
67 68 69 | |
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 | |
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 | |
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 | |
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 | |
append
¶
append(value)
Append to a sequence node.
Source code in python/pyrs_yaml/node.py
148 149 150 | |
insert
¶
insert(index, value)
Insert into a sequence node at index.
Source code in python/pyrs_yaml/node.py
152 153 154 | |
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 | |
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 | |
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 | |
remove_comment
¶
remove_comment()
Remove this node's comment.
Source code in python/pyrs_yaml/node.py
185 186 187 | |
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 | |
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 | |
set_anchor
¶
set_anchor(name)
Set (or replace) this node's anchor.
Source code in python/pyrs_yaml/node.py
243 244 245 | |
remove_anchor
¶
remove_anchor()
Remove this node's anchor.
Source code in python/pyrs_yaml/node.py
247 248 249 | |
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 | |
remove_tag
¶
remove_tag()
Remove this node's YAML tag.
Source code in python/pyrs_yaml/node.py
266 267 268 | |
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 | |
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 | |
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 | |
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 | |
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 | |
walk
¶
walk()
Walk all descendant nodes (depth-first pre-order).
Source code in python/pyrs_yaml/node.py
359 360 361 362 363 | |
filter
¶
filter(predicate)
Filter descendant nodes by a predicate function.
Source code in python/pyrs_yaml/node.py
365 366 367 | |
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 | |
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 | |
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 | |