### Basic ruamel.yaml Setup Source: https://yaml.dev/doc/ruamel.yaml/detail Standard import and instantiation for using ruamel.yaml. This setup is assumed for most examples unless otherwise specified. ```python from ruamel.yaml import YAML yaml = YAML() ``` -------------------------------- ### Install ruamel.yaml with C extensions Source: https://yaml.dev/doc/ruamel.yaml Use this command to install ruamel.yaml along with its C extensions, ensuring proper dependency handling. This is recommended over directly installing `ruamel.yaml.clibz` or `ruamel.yaml.clib`. ```bash python -m pip install --no-deps ruamel.yaml ruamel.yaml.clib ``` -------------------------------- ### Install ruamel.yaml Source: https://yaml.dev/doc/ruamel.yaml/install Install the core ruamel.yaml package from PyPI. This is the standard installation command. ```bash pip install ruamel.yaml ``` -------------------------------- ### YAML Anchors, References, and Merging Source: https://yaml.dev/doc/ruamel.yaml/example Illustrates how ruamel.yaml preserves handcrafted YAML anchors and references, and how merged keys can be accessed. This example requires ruamel.yaml to be installed. ```python from ruamel.yaml import YAML inp = """ - &CENTER {x: 1, y: 2} - &LEFT {x: 0, y: 2} - &BIG {r: 10} - &SMALL {r: 1} # All the following maps are equal: # Explicit keys - x: 1 y: 2 r: 10 label: center/big # Merge one map - <<: *CENTER r: 10 label: center/big # Merge multiple maps - <<: [*CENTER, *BIG] label: center/big """ ``` -------------------------------- ### Install ruamel.yaml with libyaml support Source: https://yaml.dev/doc/ruamel.yaml Install ruamel.yaml with optional support for libyaml. This is the preferred method over using the older C extensions directly. ```bash python -m pip install ruamel.yaml[libyaml] ``` -------------------------------- ### Install ruamel.yaml command-line utility Source: https://yaml.dev/doc/ruamel.yaml/install Install the command-line utility for ruamel.yaml, which allows for round-trip testing, re-indenting, and conversion of YAML files. ```bash pip install ruamel.yaml.cmd ``` -------------------------------- ### Install ruamel.yaml with old libyaml support Source: https://yaml.dev/doc/ruamel.yaml Install ruamel.yaml with optional support for the older libyaml. This is an alternative to using the newer libyaml support. ```bash python -m pip install ruamel.yaml[oldlibyaml] ``` -------------------------------- ### Load with CSafeLoader, Dump with RoundTripLoader (Version >= 0.15) Source: https://yaml.dev/doc/ruamel.yaml/api This example shows loading YAML with 'CSafeLoader' and dumping with 'RoundTripLoader' for ruamel.yaml versions 0.15 and above. It requires two YAML instances for different loading and dumping types, with options for width and explicit start. ```python if ruamel.yaml.version_info < (0, 15): data = yaml.load(istream, Loader=yaml.CSafeLoader) yaml.round_trip_dump(data, ostream, width=1000, explicit_start=True) else: yml = ruamel.yaml.YAML(typ='safe') data = yml.load(istream) ymlo = ruamel.yaml.YAML() # or yaml.YAML(typ='rt') ymlo.width = 1000 ymlo.explicit_start = True ymlo.dump(data, ostream) ``` -------------------------------- ### Install ruamel.yaml with Jinja2 support Source: https://yaml.dev/doc/ruamel.yaml/install Install ruamel.yaml with support for processing jinja2/YAML templates. You might need to quote the argument. ```bash pip install ruamel.yaml[jinja2] ``` -------------------------------- ### Update pip, setuptools, and wheel Source: https://yaml.dev/doc/ruamel.yaml/install Ensure you have the latest versions of pip, setuptools, and wheel installed. This is recommended before installing ruamel.yaml. ```bash pip install -U pip setuptools wheel ``` -------------------------------- ### Install Python development headers on Debian Source: https://yaml.dev/doc/ruamel.yaml/install Install the Python 3 development headers on Debian-based systems. This is required for using the faster C loader and emitter. ```bash sudo apt-get install python3-dev ``` -------------------------------- ### Combined Indentation Settings Source: https://yaml.dev/doc/ruamel.yaml/detail Configure indentation for both mappings and sequences, along with an offset. This example uses `mapping=2`, `sequence=4`, and `offset=2` for specific formatting. ```python yaml.indent(mapping=2, sequence=4, offset=2) ``` -------------------------------- ### Basic YAML Round Trip and Modification Source: https://yaml.dev/doc/ruamel.yaml/example Demonstrates parsing YAML into Python objects, modifying them, and then dumping the modified objects back to YAML. Ensure ruamel.yaml is installed and sys is imported for stdout. ```python import sys from ruamel.yaml import YAML inp = """ # example name: # details family: Smith # very common given: Alice # one of the siblings """ yaml = YAML() code = yaml.load(inp) code['name']['given'] = 'Bob' yaml.dump(code, sys.stdout) ``` -------------------------------- ### Install Python development headers on CentOS Source: https://yaml.dev/doc/ruamel.yaml/install Install the Python development headers on CentOS 7 systems. This is required for using the faster C loader and emitter. ```bash sudo yum install python-devel ``` -------------------------------- ### Load YAML Data Source: https://yaml.dev/doc/ruamel.yaml/example Loads YAML data from a string and asserts a specific value. This is a basic example of data loading. ```python from ruamel.yaml import YAML yaml = YAML() data = yaml.load(inp) assert data[7]['y'] == 2 ``` -------------------------------- ### Incorrect Class Loading with ruamel.yaml Source: https://yaml.dev/doc/ruamel.yaml/dumpcls This example demonstrates an incorrect way to implement `from_yaml` for a class, leading to issues with nested object loading. It directly constructs the class instance, which fails for recursive or deeply nested structures. ```python from pathlib import Path import ruamel.yaml class Person: def __init__(self, name, siblings=None): self.name = name self.siblings = [] if siblings is None else siblings def __repr__(self): return f'Person(name: {self.name}, siblings: {self.siblings})' @classmethod def from_yaml(cls, constructor, node): data = ruamel.yaml.CommentedMap() constructor.construct_mapping(node, maptyp=data, deep=True) return cls(**data) path = Path('/tmp/arya.yaml') yaml = ruamel.yaml.YAML() yaml.register_class(Person) data = yaml.load(path) print(data) ``` -------------------------------- ### Dump YAML with Output Transformation Source: https://yaml.dev/doc/ruamel.yaml/basicuse Apply a custom transformation function to the dumped YAML output. This example replaces newlines with '<\n', resulting in invalid YAML. ```python def tr(s): return s.replace(' ', '< ') # such output is not valid YAML! yaml.dump(data, sys.stdout, transform=tr) ``` -------------------------------- ### Control Compact Notation for Nested Collections Source: https://yaml.dev/doc/ruamel.yaml/example Illustrates how to disable compact notation for sequences containing sequences or mappings using `yaml.compact()`. Setting `seq_seq` or `seq_map` to `False` forces nested collections to start on a new line. ```python import sys from ruamel.yaml import YAML d = [dict(b=2), [3, 4]] yaml = YAML() yaml.dump(d, sys.stdout) print('='*15) yaml = YAML() yaml.compact(seq_seq=False, seq_map=False) yaml.dump(d, sys.stdout) ``` -------------------------------- ### Setting Sequence Indentation Source: https://yaml.dev/doc/ruamel.yaml/detail Control the indentation of block sequence items. `sequence=4` indents sequence elements by 4 spaces relative to the block's start. ```python yaml.indent(sequence=4) ``` -------------------------------- ### Load and Dump using pathlib.Path (Version >= 0.15) Source: https://yaml.dev/doc/ruamel.yaml/api Demonstrates loading and dumping YAML data directly using pathlib.Path instances for input and output files. This approach is suitable for ruamel.yaml versions 0.15 and above and utilizes a custom MyYAML class for specific configurations like preserving quotes and indentation. ```python # in myyaml.py if ruamel.yaml.version_info < (0, 15): class MyYAML(yaml.YAML): def __init__(self): yaml.YAML.__init__(self) self.preserve_quotes = True self.indent(mapping=4, sequence=4, offset=2) # in your code try: from myyaml import MyYAML except (ModuleNotFoundError, ImportError): if ruamel.yaml.version_info >= (0, 15): raise # some pathlib.Path from pathlib import Path inf = Path('/tmp/in.yaml') outf = Path('/tmp/out.yaml') if ruamel.yaml.version_info < (0, 15): with inf.open() as ifp: data = yaml.round_trip_load(ifp, preserve_quotes=True) with outf.open('w') as ofp: yaml.round_trip_dump(data, ofp, indent=4, block_seq_indent=2) else: yml = MyYAML() # no need for with statement when using pathlib.Path instances data = yml.load(inf) yml.dump(data, outf) ``` -------------------------------- ### Old API: Safe Load and Dump Source: https://yaml.dev/doc/ruamel.yaml/api Demonstrates the usage of `safe_load` and `safe_dump` with file paths and output streams using the older API structure. ```python from pathlib import Path from ruamel import yaml data = yaml.safe_load("abc: 1") out = Path('/tmp/out.yaml') with out.open('w') as fp: yaml.safe_dump(data, fp, default_flow_style=False) ``` -------------------------------- ### Register and Load Dataclass with __post_init__ Source: https://yaml.dev/doc/ruamel.yaml/dumpcls Demonstrates registering a dataclass with a custom YAML tag and loading it. The __post_init__ method is automatically called after initialization, as shown by the calculated 'xyz' attribute. ```python from typing import ClassVar from dataclasses import dataclass import ruamel.yaml @dataclass class DC: yaml_tag: ClassVar = '!dc_example' # if you don't want !DC as tag abc: int klm: int xyz: int = 0 def __post_init__(self) -> None: self.xyz = self.abc + self.klm yaml = ruamel.yaml.YAML() yaml.register_class(DC) dc = DC(abc=5, klm=42) assert dc.xyz == 47 yaml_str = """ !dc_example abc: 13 klm: 37 """ dc2 = yaml.load(yaml_str) print(f'{dc2.xyz=}') ``` -------------------------------- ### New API: Safe Load and Dump Source: https://yaml.dev/doc/ruamel.yaml/api Illustrates the new API for loading and dumping YAML data using a `YAML` instance, setting configuration like `default_flow_style` on the instance. ```python from pathlib import Path from ruamel.yaml import YAML yaml = YAML(typ='safe') yaml.default_flow_style = False data = yaml.load("abc: 1") out = Path('/tmp/out.yaml') yaml.dump(data, out) ``` -------------------------------- ### Generate PDF documentation with ryd Source: https://yaml.dev/doc/ruamel.yaml/contributing Use the ryd command-line tool to generate PDF documentation from .ryd files. Ensure the PDFs look acceptable before submitting a pull-request. ```bash ryd --pdf '**/*.ryd' ``` -------------------------------- ### Configure YAML Instance Source: https://yaml.dev/doc/ruamel.yaml/api Configure a YAML instance by setting attributes like 'allow_unicode' and 'unicode_supplementary'. 'allow_unicode' controls Unicode output, and 'unicode_supplementary' enforces specific formats for supplementary characters if 'allow_unicode' is True. ```python yaml = YAML(typ='safe', pure=True) yaml.allow_unicode = False ``` -------------------------------- ### New API: Loading Multiple Documents Source: https://yaml.dev/doc/ruamel.yaml/api Demonstrates loading multiple YAML documents from a stream into a Python list using the `load_all` method on a `YAML` instance. ```python yaml = YAML() data = list(yaml.load_all(in_path)) ``` -------------------------------- ### Configure flake8 for ruamel.yaml Source: https://yaml.dev/doc/ruamel.yaml/contributing This is a sample configuration file for flake8, used for checking Python code style. It specifies showing the source code for errors and sets the maximum line length. ```ini [flake8] show-source = True max-line-length = 95 ignore = F405 ``` -------------------------------- ### Load and Dump using SafeLoader (Version < 0.15) Source: https://yaml.dev/doc/ruamel.yaml/api This code block demonstrates loading and dumping YAML data using the 'safe_load' and 'safe_dump' functions, compatible with ruamel.yaml versions prior to 0.15. ```python if ruamel.yaml.version_info < (0, 15): data = yaml.safe_load(istream) yaml.safe_dump(data, ostream) else: yml = ruamel.yaml.YAML(typ='safe', pure=True) # 'safe' load and dump data = yml.load(istream) yml.dump(data, ostream) ``` -------------------------------- ### Dump All Documents using YAML Context Manager Source: https://yaml.dev/doc/ruamel.yaml/api Use the YAML() context manager to dump all loaded documents from a file. Ensure 'explicit_start' is set to True for multi-document output. This method automatically handles multi-document creation when 'dump()' is called more than once within the context. ```python with YAML(output=sys.stdout) as yaml: yaml.explicit_start = True for data in yaml.load_all(Path(multi_document_filename)): # do something on data yaml.dump(data) ``` -------------------------------- ### Explicitly Load YAML 1.1 Source: https://yaml.dev/doc/ruamel.yaml/pyyaml Load a YAML document as version 1.1 by including '%YAML 1.1' at the beginning of the file. Otherwise, ruamel.yaml defaults to YAML 1.2. ```yaml %YAML 1.1 ``` -------------------------------- ### Dump Multiple YAML Documents with Custom Sequence Indentation Source: https://yaml.dev/doc/ruamel.yaml/example Demonstrates dumping the same data structure multiple times to create a stream of documents. It also shows how to use a custom `transform` function to modify sequence indentation. ```python import sys from ruamel.yaml import YAML data = {1: {1: [{1: 1, 2: 2}, {1: 1, 2: 2}], 2: 2}, 2: 42} yaml = YAML() yaml.explicit_start = True yaml.dump(data, sys.stdout) yaml.indent(sequence=4, offset=2) yaml.dump(data, sys.stdout) def sequence_indent_four(s): # this will fail on direclty nested lists: {1; [[2, 3], 4]} levels = [] ret_val = '' for line in s.splitlines(True): ls = line.lstrip() indent = len(line) - len(ls) if ls.startswith('- '): if not levels or indent > levels[-1]: levels.append(indent) elif levels: if indent < levels[-1]: levels = levels[:-1] # same -> do nothing else: if levels: if indent <= levels[-1]: while levels and indent <= levels[-1]: levels = levels[:-1] ret_val += ' ' * len(levels) + line return ret_val yaml = YAML() yaml.explicit_start = True yaml.dump(data, sys.stdout, transform=sequence_indent_four) ``` -------------------------------- ### Load YAML with Safe Type Source: https://yaml.dev/doc/ruamel.yaml/basicuse Instantiate YAML with typ='safe' to load documents without resolving unknown tags. This is useful for security when dealing with untrusted input. ```python from ruamel.yaml import YAML yaml=YAML(typ='safe') # default, if not specfied, is 'rt' (round-trip) yaml.load(doc) ``` -------------------------------- ### New API: Allowing Duplicate Keys Source: https://yaml.dev/doc/ruamel.yaml/api Shows how to enable the allowance of duplicate keys in mappings when loading YAML streams using the new API by setting `allow_duplicate_keys` to `True`. ```python yaml = ruamel.yaml.YAML() yaml.allow_duplicate_keys = True yaml.load(stream) ``` -------------------------------- ### Run mypy for Python typing checks Source: https://yaml.dev/doc/ruamel.yaml/contributing Execute mypy with specific flags to check Python 2.7 compatible typing information. This command should be run from the directory containing the ruamel directory. ```bash mypy --py2 --strict --follow-imports silent ruamel/yaml/*.py ``` -------------------------------- ### Dump dictionary to stdout using standard YAML class Source: https://yaml.dev/doc/ruamel.yaml/example Illustrates the standard way to dump a Python dictionary to standard output using the dump method with sys.stdout. This is the recommended approach for writing YAML to a stream. ```python yaml.dump((dict(a=1, b=2)), sys.stdout) print() # or sys.stdout.write('\n') ``` -------------------------------- ### Combine Multiple YAML Documents from Files Source: https://yaml.dev/doc/ruamel.yaml/api Combine YAML documents from a list of filenames into a single output stream. Each file is opened, its content loaded, and then dumped to the output. The final output is a uniformly indented YAML file. ```python list_of_filenames = ['x.yaml', 'y.yaml', ] with YAML(output=sys.stdout) as yaml: yaml.explicit_start = True for path in list_of_filename: with open(path) as fp: yaml.dump(yaml.load(fp)) ``` -------------------------------- ### Registering a Class for Dumping Source: https://yaml.dev/doc/ruamel.yaml/dumpcls Register a custom class with the YAML instance to allow it to be dumped. Ensure the class has an __init__ method. ```python import sys import ruamel.yaml class User: def __init__(self, name, age): self.name = name self.age = age yaml = ruamel.yaml.YAML() yaml.register_class(User) yaml.dump([User('Anthon', 18)], sys.stdout) ``` -------------------------------- ### Correct Class Loading with ruamel.yaml using yield Source: https://yaml.dev/doc/ruamel.yaml/dumpcls This corrected `from_yaml` implementation uses `yield` to return an empty instance of the class first. This allows ruamel.yaml to recursively load nested objects into the yielded instance, resolving issues with self-referential or deeply nested structures. ```python from pathlib import Path import ruamel.yaml class Person: def __init__(self, name, siblings=None): self.name = name self.siblings = [] if siblings is None else siblings def __repr__(self): return f'Person(name: {self.name}, siblings: {self.siblings})' @classmethod def from_yaml(cls, constructor, node): person = Person(name='') yield person data = ruamel.yaml.CommentedMap() constructor.construct_mapping(node, maptyp=data, deep=True) for k, v in data.items(): setattr(person, k, v) path = Path('/tmp/arya.yaml') yaml = ruamel.yaml.YAML() yaml.register_class(Person) data = yaml.load(path) print(data) ``` -------------------------------- ### Load YAML using C-based SafeLoader Source: https://yaml.dev/doc/ruamel.yaml/basicuse Load YAML using the C-based SafeLoader, which inherits from libyaml/PyYAML. Note that it loads octal numbers like '0o52' and '052' as integers. ```python from ruamel.yaml import YAML yaml=YAML(typ="safe") yaml.load("""a:\n b: 2\n c: 3\n""") ``` -------------------------------- ### Dump dictionary to string using custom YAML class Source: https://yaml.dev/doc/ruamel.yaml/example Demonstrates how to use the custom MyYAML class to dump a Python dictionary into a string. This method is more efficient than the old API's approach. ```python print(yaml.dump(dict(a=1, b=2))) ``` -------------------------------- ### Set YAML Document Version Source: https://yaml.dev/doc/ruamel.yaml/detail Explicitly set the YAML document version using '%YAML 1.x'. Supported versions for 'x' are 1 or 2. Defaults to 1.2 if not specified. ```yaml %YAML 1.x ``` -------------------------------- ### Using @yaml.register_class Decorator Source: https://yaml.dev/doc/ruamel.yaml/dumpcls Apply the `@yaml.register_class` decorator directly to the class to register it with an existing YAML instance. This method also requires `yaml_tag`, `to_yaml`, and `from_yaml` to be defined for custom serialization. ```python import sys import ruamel.yaml yaml = ruamel.yaml.YAML() @yaml.register_class class User: yaml_tag = u'!user' def __init__(self, name, age): self.name = name self.age = age @classmethod def to_yaml(cls, representer, node): return representer.represent_scalar(cls.yaml_tag, u'{.name}-{.age}'.format(node, node)) @classmethod def from_yaml(cls, constructor, node): return cls(*node.value.split('-')) yaml.dump([User('Anthon', 18)], sys.stdout) ``` -------------------------------- ### Insert Key with Comment in CommentedMap Source: https://yaml.dev/doc/ruamel.yaml/example Demonstrates inserting a new key-value pair into a CommentedMap at a specific position, including an optional comment. The comment is aligned with its neighbors. ```python import sys from ruamel.yaml import YAML yaml_str = """ first_name: Art occupation: Architect # This is an occupation comment about: Art Vandelay is a fictional character that George invents... """ yaml = YAML() data = yaml.load(yaml_str) data.insert(1, 'last name', 'Vandelay', comment="new key") yaml.dump(data, sys.stdout) ``` -------------------------------- ### Customize Indentation for Mappings and Sequences Source: https://yaml.dev/doc/ruamel.yaml/example Shows how to change the default indentation for mappings and sequences using `yaml.indent()`. The `mapping`, `sequence`, and `offset` parameters control the indentation levels. ```python import sys from ruamel.yaml import YAML d = dict(a=dict(b=2),c=[3, 4]) yaml = YAML() yaml.dump(d, sys.stdout) print('#123456789') yaml = YAML() yaml.indent(mapping=4, sequence=6, offset=3) yaml.dump(d, sys.stdout) print('#123456789') ``` -------------------------------- ### Customizing Tag and Serialization Methods Source: https://yaml.dev/doc/ruamel.yaml/dumpcls Define a custom YAML tag and implement `to_yaml` and `from_yaml` class methods for explicit control over serialization and deserialization. The `yaml_tag` attribute specifies the tag name. ```python import sys import ruamel.yaml class User: yaml_tag = u'!user' def __init__(self, name, age): self.name = name self.age = age @classmethod def to_yaml(cls, representer, node): return representer.represent_scalar(cls.yaml_tag, u'{.name}-{.age}'.format(node, node)) @classmethod def from_yaml(cls, constructor, node): return cls(*node.value.split('-')) yaml = ruamel.yaml.YAML() yaml.register_class(User) yaml.dump([User('Anthon', 18)], sys.stdout) ``` -------------------------------- ### Setting Mapping Indentation Source: https://yaml.dev/doc/ruamel.yaml/detail Control the indentation of mapping values. `mapping=4` indents mapping values by 4 spaces. ```python yaml.indent(mapping=4) ``` -------------------------------- ### Using @yaml_object Decorator Source: https://yaml.dev/doc/ruamel.yaml/dumpcls Use the `@yaml_object` decorator to register a class with the YAML instance. This requires moving the `YAML()` instantiation earlier in the script. The `yaml_tag`, `to_yaml`, and `from_yaml` methods function as before. ```python import sys from ruamel.yaml import YAML, yaml_object yaml = YAML() @yaml_object(yaml) class User: yaml_tag = u'!user' def __init__(self, name, age): self.name = name self.age = age @classmethod def to_yaml(cls, representer, node): return representer.represent_scalar(cls.yaml_tag, u'{.name}-{.age}'.format(node, node)) @classmethod def from_yaml(cls, constructor, node): return cls(*node.value.split('-')) yaml.dump([User('Anthon', 18)], sys.stdout) ``` -------------------------------- ### Load YAML using Pure Python SafeLoader Source: https://yaml.dev/doc/ruamel.yaml/basicuse Load YAML using the pure Python SafeLoader, which supports YAML 1.2. It correctly loads octal numbers like '052' as the integer 52. ```python from ruamel.yaml import YAML yaml=YAML(typ="safe", pure=True) yaml.load("""a:\n b: 2\n c: 3\n""") ``` -------------------------------- ### Custom YAML dumper for string output Source: https://yaml.dev/doc/ruamel.yaml/example Subclass YAML to override the dump method, allowing it to return a string representation when no stream is provided. This is useful for capturing YAML output directly as a string. ```python import sys from ruamel.yaml import YAML from ruamel.yaml.compat import StringIO class MyYAML(YAML): def dump(self, data, stream=None, **kw): inefficient = False if stream is None: inefficient = True stream = StringIO() YAML.dump(self, data, stream, **kw) if inefficient: return stream.getvalue() yaml = MyYAML() # or typ='safe'/'unsafe' etc ``` -------------------------------- ### Dump YAML to a Stream Source: https://yaml.dev/doc/ruamel.yaml/basicuse Dump a Python dictionary to a stream (e.g., file pointer or sys.stdout). Set default_flow_style to False for block style output. ```python from ruamel.yaml import YAML yaml=YAML() yaml.default_flow_style = False yaml.dump({'a': [1, 2]}, s) ``` -------------------------------- ### Loading Output with Self-Referential Objects Source: https://yaml.dev/doc/ruamel.yaml/dumpcls Load YAML data containing self-referential objects back into Python objects. Ensure the class has an appropriate `__repr__` for clear output. The `register_class` method is used to make the YAML instance aware of the `Person` class. ```python from pathlib import Path import ruamel.yaml class Person: def __init__(self, name, siblings=None): self.name = name self.siblings = [] if siblings is None else siblings def __repr__(self): return f'Person(name: {self.name}, siblings: {self.siblings})' path = Path('/tmp/arya.yaml') yaml = ruamel.yaml.YAML() yaml.register_class(Person) data = yaml.load(path) print(data) ``` -------------------------------- ### Handling Self-Referential Objects During Dumping Source: https://yaml.dev/doc/ruamel.yaml/dumpcls When dumping objects with self-references, create an empty object first and yield it. Then, populate its content. This ensures that if the same node is encountered while processing content, an ID is created for the yielded object, allowing for correct assignment. ```python from pathlib import Path import ruamel.yaml class Person: def __init__(self, name, siblings=None): self.name = name self.siblings = [] if siblings is None else siblings arya = Person('Arya') sansa = Person('Sansa') arya.siblings.append(sansa) # there are better ways to represent this sansa.siblings.append(arya) yaml = ruamel.yaml.YAML() yaml.register_class(Person) path = Path('/tmp/arya.yaml') yaml.dump(arya, path) print(path.read_text()) ``` -------------------------------- ### Setting Indentation Offset Source: https://yaml.dev/doc/ruamel.yaml/detail Adds an additional offset to the indentation of sequence items. `offset=2` pushes the dash inwards by 2 spaces within the `sequence` indentation. ```python yaml.indent(sequence=4, offset=2) ``` -------------------------------- ### Access Nested Data with mlget Source: https://yaml.dev/doc/ruamel.yaml/detail Use the `mlget` method to access nested data within loaded YAML structures. It supports specifying paths as a list and includes an option `list_ok` for handling list indices. ```python yaml_str = """ a: - b: c: 42 - d: f: 196 e: g: 3.14 """ data = yaml.load(yaml_str) assert data.mlget(['a', 1, 'd', 'f'], list_ok=True) == 196 ``` -------------------------------- ### Add/Replace Comments in YAML Source: https://yaml.dev/doc/ruamel.yaml/detail Demonstrates adding or replacing end-of-line comments on block-style collections using `yaml_add_eol_comment`. The column for the comment is derived from surrounding comments. ```python from __future__ import print_function import sys import ruamel.yaml yaml = ruamel.yaml.YAML() inp = """ abc: - a # comment 1 xyz: a: 1 # comment 2 b: 2 c: 3 d: 4 e: 5 f: 6 # comment 3 """ data = yaml.load(inp) data['abc'].append('b') data['abc'].yaml_add_eol_comment('comment 4', 1) # takes column of comment 1 data['xyz'].yaml_add_eol_comment('comment 5', 'c') # takes column of comment 2 data['xyz'].yaml_add_eol_comment('comment 6', 'e') # takes column of comment 3 data['xyz'].yaml_add_eol_comment('comment 7\n\n# that\'s all folks', 'd', column=20) yaml.dump(data, sys.stdout) ``` -------------------------------- ### Explicitly Setting Top-Level Colon Alignment Width Source: https://yaml.dev/doc/ruamel.yaml/detail Manually set the width for aligning colons in top-level mappings. Specify an integer, e.g., `12`, which should be one more than the widest key. ```python yaml.top_level_colon_align = 12 ``` -------------------------------- ### Enabling Top-Level Colon Alignment Source: https://yaml.dev/doc/ruamel.yaml/detail Align colons in top-level mappings based on the longest key. Set `yaml.top_level_colon_align = True` for automatic alignment or an integer for a fixed width. ```python yaml.top_level_colon_align = True ``` -------------------------------- ### Set Maximum Recursion Depth in ruamel.yaml Source: https://yaml.dev/doc/ruamel.yaml/cve Set the maximum depth for nested data structures when loading YAML. This helps prevent potential 'out of memory' or 'recursion depth overflow' issues with large or deeply nested inputs. The default for Docker's compose.yaml files is 4. ```python yaml = ruamel.yaml.YAML() yaml.max_depth = 42 ``` -------------------------------- ### Adding Prefix Space Before Colon Source: https://yaml.dev/doc/ruamel.yaml/detail Insert an extra space between a mapping key and its colon. `yaml.prefix_colon = ' '` adds this space, except when `top_level_colon_align` is active. ```python yaml.prefix_colon = ' ' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.