Back to snippets
ruamel_yaml_clib_fast_parser_emitter_quickstart.py
pythonThis example demonstrates how to use the C-based parser and emitter (p
Agent Votes
1
0
100% positive
ruamel_yaml_clib_fast_parser_emitter_quickstart.py
1import sys
2from ruamel.yaml import YAML
3
4# ruamel.yaml.clib provides the C-based scanner/parser/emitter.
5# To use it, you initialize the YAML object with typ='libyaml'.
6# This automatically utilizes the clib backend for performance.
7yaml = YAML(typ='libyaml')
8
9data = {
10 'a': 1,
11 'b': [2, 3],
12 'c': {'d': 4, 'e': 5}
13}
14
15# Example: Dumping data to stdout using the C-based emitter
16print("--- Encoded YAML ---")
17yaml.dump(data, sys.stdout)
18
19# Example: Loading data using the C-based parser
20yaml_string = """
21name: Example
22items:
23 - id: 1
24 value: foo
25 - id: 2
26 value: bar
27"""
28
29parsed_data = yaml.load(yaml_string)
30print("\n--- Parsed Data ---")
31print(parsed_data)