YamlDocument Class
YamlDocument Class¶
The YamlDocument class represents a parsed YAML document with full metadata preservation.
Overview¶
class YamlDocument:
"""A parsed YAML document with perfect round-trip support."""
Methods¶
to_yaml()¶
Convert the document back to a YAML string.
to_yaml() -> str
Returns: The complete YAML document string, ending with a newline.
Example:
doc = pyrs_yaml.parse("key: value")
print(doc.to_yaml()) # key: value\n
to_yaml_with_options()¶
Convert to YAML with custom options.
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
Parameters:
indent_size— Spaces per indent level (default: 2)explicit_start— Add---at document start (default: False)explicit_end— Add...at document end (default: False)sort_keys— Sort keys alphabetically (default: False); a mapping that both defines and uses an anchor name locally keeps its source order, so sorting never writes an alias above the&nameit resolves tonote_placement— Where a note goes when it cannot ride its line and an&a/!tagheader line sits above it:note_first(default) writes it above the header, where a read files it, so the first emission settles;header_firstkeeps it inside the gap. Any other value is refused
Example:
yaml_str = doc.to_yaml_with_options(
indent_size=4,
explicit_start=True,
sort_keys=True,
)
to_dict()¶
Convert to a Python dict/list, resolving alias references.
to_dict() -> dict[Any, Any] | list[Any]
Returns: Native Python types. Anchors (&name) are inlined, aliases (*name) are replaced with actual values. Scalars are converted to Python native types (bool/int/float/str/None). The same resolution applies to mapping keys, so ~: 1 loads with a None key and 1: a with the integer 1 - one text, one type, whichever side of the : it sits on.
Example:
data = doc.to_dict()
print(data["key"]) # value
print(type(data)) # <class 'dict'>
get()¶
Get a value by top-level mapping key (literal key lookup, consistent with
__getitem__/__setitem__).
get(key: str, default: Any = None) -> Any
Parameters:
key— The literal mapping key to look up. Keys may legally contain.,[,]or$; they are never interpreted as paths.default— Value to return if the key is not found (default: None)
Returns: The value, or default if not found (or if root is not a mapping).
Path access
For JSONPath-style access, use find() / node() /
set() instead — they resolve paths such as $.a.b and
$.items[-1].
Example:
value = doc.get("key")
value = doc.get("a.b") # literal dotted key
value = doc.get("missing", "fallback")
root_type()¶
Get the root node type as a string.
root_type() -> str
Returns: One of "scalar", "mapping", "sequence", "null".
"alias" is a spelling the binding carries for an alias root, but no document read reaches it: an
alias needs its anchor earlier in the same document, so a root alias is refused by the parser.
pyrs_yaml.parse("*x\n") answers YamlParseError: YAML parse error: while parsing node, found
unknown anchor at char 0 line 1 column 1, and the cross-document form "--- &a 1\n--- *a\n" is
refused the same way at line 2.
Example:
print(doc.root_type()) # "mapping"
to_json()¶
Serialize the document to a JSON string.
to_json(indent: int = 2) -> str
Parameters:
indent— JSON indentation spaces (default: 2)
Returns: A JSON string of the document contents.
Example:
doc = pyrs_yaml.parse("a: 1\nb: hello")
json_str = doc.to_json() # '{"a": 1, "b": "hello"}'
validate()¶
Validate the document contents against a JSON Schema.
validate(schema: str | dict[str, Any]) -> None
Parameters:
schema— JSON Schema as either a JSON string or a Python dict
Returns: None on success.
Raises:
YamlValidateError— The document does not conform to the schema, or the schema argument is unusable. Astrthat is not JSON is refused withschema text must be JSON (…); pass the schema as a dict if it is not JSON, and an argument that is neitherstrnor a mapping arrives here too, with the engine's sentence as its text:doc.validate(3)answersTypeError: argument of type 'int' is not iterable
Evaluation is delegated to the Python jsonschema package, which no extra this project publishes
installs: run pip install jsonschema before validating. With jsonschema unimportable,
doc.validate({"type": "object"}) still answers a YamlValidateError, whose message names that
install route and carries the import error. It is recorded with its reproduction in
Exceptions — YamlValidateError.
Example:
doc = pyrs_yaml.parse("name: Alice\nage: 30")
doc.validate({"type": "object", "properties": {"name": {"type": "string"}}})
# From JSON string
doc.validate('{"type": "object", "required": ["name"]}')
source()¶
Return the original YAML source text used to create this document. If the document has been edited in place, the source is lazily re-serialized from the current tree on first access.
source() -> str
Returns: The YAML string. Empty string if the document was not created via parse() (e.g. from from_dict()).
Example:
doc = pyrs_yaml.parse("key: value")
print(doc.source()) # "key: value"
flush_source()¶
flush_source() -> None
Lazily re-serializes the AST into source when edits have occurred, so source reflects the current tree without a full dump after every mutation.
reparse()¶
Re-parse the stored source text in place, allowing schema or merge behavior changes.
reparse(resolve_merges: bool = True, schema: str | None = None, honor_version_directive: bool | None = None) -> None
Parameters:
resolve_merges— Whether to resolve<<: *aliasmerge keys (default:True)schema— Type resolution schema:"core","json","failsafe", or"yaml1.1".Nonekeeps the schema the document was read with.honor_version_directive— Version negotiation for a declared%YAML.Trueresolves a document declaring%YAML 1.1under the 1.1 profile and re-emits the directive;Falseignores the declaration and keeps the selected schema.Nonekeeps the document's current setting.
Raises:
TypeError— No source text storedYamlParseError— Re-parsing failed
Example:
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)
Editing Methods¶
Atomic edits
All edits are atomic — a failed edit leaves the document (and its
revision) untouched. On success the stored source is marked dirty and
the next source() / to_yaml() / to_yaml_with_options() / reparse()
call re-serializes from the updated tree. See the
In-Place Editing guide for the full path syntax
and semantics.
set()¶
Set a value by JSONPath path.
set(path: str, value: Any, create_missing: bool = False) -> None
doc = pyrs_yaml.parse("a:\n b: 1")
doc.set("$.a.b", 42) # replace existing
doc.set("$.a.c", True) # create new key
doc.set("$", {"x": 1}) # replace the root
empty = pyrs_yaml.parse("")
empty.set("$.a", 1) # auto-creates a mapping root: {a: 1}
Raises:
YamlPathError— Malformed path (wildcards/..are rejected)YamlEditError— A path step that cannot be applied, named in the message:edit failed: cannot-edit-aliasfor a step through an alias,create-needs-mappingfor a step into a scalar or onto the wrong container shape,cannot-descend-into-scalar:<segment>whencreate_missing=Truemeets a scalar,missing-path:<key>for a key that is missing before the one being written,index-out-of-range-edit:<index>for an index past the sequence. A missing final key is not a refusal —parse("a: 1\n").set("$.zz", 3)emitsa: 1\nzz: 3\n— and neither is writing the source of a live anchor:set("$.base", 2)onbase: &x 1\nuse: *x\nre-emitsbase: &x 2\nuse: *x\n, keeping&xwhere its alias still finds itYamlTypeError— Value of a Python type the writer does not know; atupleis accepted and written as a sequence, andbytesis accepted as!!binary
The full measured vocabulary, call by call, is Edit reason tokens.
walk()¶
Depth-first, pre-order traversal of the AST, yielding Node objects.
walk() -> Generator[Node, None, None]
Unlike Node.walk(), this method is Rust-backed — it traverses the AST directly without converting to Python dicts, making it significantly faster for large documents.
Yields: Node objects for every node in the document tree, including the root.
Example:
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()¶
Like walk(), but yields only scalar/null nodes.
scalars() -> Generator[Node, None, None]
Yields: Node objects for every scalar or null node in the document tree.
Example:
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 a value into a sequence at an index. The path must resolve to a sequence. Negative indexes count from the end (-1 inserts before the last element).
insert(path: str, index: int, value: Any) -> None
doc = pyrs_yaml.parse("items: [a, c]")
doc.insert("$.items", 1, "b") # items: [a, b, c]
doc.insert("$.items", -1, "x") # items: [a, b, x, c]
Raises:
YamlEditError—edit failed: not-a-sequencewhen the path resolves to a mapping or a scalar,edit failed: index-out-of-range-editfor an index abovelenor below-len,edit failed: missing-path:<key>for a path that does not resolve,edit failed: cannot-edit-aliasfor a path through an alias,edit failed: cannot-descend-into-scalar:<segment>for a path under a scalar value
append()¶
Append a value to a sequence. The path must resolve to a sequence.
append(path: str, value: Any) -> None
doc = pyrs_yaml.parse("items: [a, b]")
doc.append("$.items", "c")
Raises: the same YamlEditError reasons as insert(), measured for a non-sequence target as edit failed: not-a-sequence and for an alias parent as edit failed: cannot-edit-alias.
delete()¶
Delete the node at a path, preserving mapping/sequence order.
delete(path: str, on_duplicate: str = "one") -> None
doc = pyrs_yaml.parse("a: 1\nb: 2\nc: 3")
doc.delete("$.b")
# a: 1
# c: 3
Raises:
YamlEditError—edit failed: missing-pathfor a key the document does not hold (this is whatdel doc["zz"]answers too),edit failed: index-out-of-range-editfor an index outside the sequence,edit failed: anchor-is-referencedwhen the node's anchor is still referenced,edit failed: duplicate-key-targetwhenon_duplicate="error"and more than one pair spells the key,edit failed: unknown on_duplicate "<value>"; expected one, all or errorfor any otheron_duplicate,edit failed: cannot-edit-aliasfor a path through an alias, andedit failed: edit-errorfordelete("$")— the root has no segment left to remove
rename()¶
Rename a mapping key in place, preserving position and key metadata.
rename(path: str, new_key: str) -> None
doc = pyrs_yaml.parse("old: 1 # comment")
doc.rename("$.old", "new")
# new: 1 # comment
Raises:
YamlEditError—edit failed: cannot-rename-rootfor$,edit failed: cannot-rename-complex-keyfor a complex key or a sequence element,edit failed: rename-key-existsfor anew_keythe mapping already holds,edit failed: missing-pathfor a path that does not resolve,edit failed: cannot-edit-aliasfor a path through an alias
Renaming a key to itself is not a refusal: measured on a: 1, rename("$.a", "a") leaves the
document as a: 1.
node()¶
Get the root Node of the document for tree navigation and editing.
node() -> Node
node = doc.node().find("$.a.b")
node.set_value(42)
find()¶
Query the document by JSONPath-like path. Supports wildcards ([*]) and deep-scan (..), returning a list when multiple nodes match.
find(path: str) -> Node | list[Node]
__setitem__() / __delitem__() — root sugar¶
doc["key"] = value # equivalent to doc.set("$.key", value)
del doc["key"] # equivalent to doc.delete("$.key")
Dunder Methods¶
__getitem__()¶
Access by key (mapping) or index (sequence).
doc["key"] # For mappings
doc[0] # For sequences
Raises:
KeyError— Key not found in mapping. Measured text isKey 'zz' not found, and because this is the builtinKeyError,str(exc)shows it quoted:"Key 'zz' not found"IndexError— Index out of range for sequence. Measured onpyrs_yaml.parse("- a\n- b\n")[99]:Index 99 out of range (len=2)TypeError— theYamlTypeErrorarm for the wrong key kind or a root that cannot be subscripted at all, each measured: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
Every text above follows pyrs_yaml.set_language() — measured under zh-CN, which answers
索引必须是整数, 键必须是字符串, YamlDocument 不支持下标操作 and
索引 99 超出范围(长度=2) for the four arms. See i18n Support.
__contains__()¶
Check if a key exists.
"key" in doc # Returns bool
__len__()¶
Get the number of items.
len(doc) # Number of keys (mapping) or items (sequence)
__iter__()¶
Iterate over keys (mapping) or values (sequence).
for key in doc:
print(key, doc[key])
__repr__()¶
Debug representation.
repr(doc) # "YamlDocument(<yaml>...)"
__str__()¶
String representation.
str(doc) # Same as doc.to_yaml()
Example¶
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
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.YamlDocument
¶
Round-trip editable YAML document with transaction support, path editing, and source preservation.
__enter__
¶
__enter__()
Enter a transaction scope: snapshot AST + splice state. with doc: exits cleanly
preserving edits; exceptions roll back the snapshot.
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.
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_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``.