### Run a complete Home Assistant configuration example Source: https://yaml.rocks/recipes/home-assistant Creates a temporary directory structure mimicking a Home Assistant setup and loads it to demonstrate !include and !secret resolution. ```python import os import tempfile import yamlrocks workdir = tempfile.mkdtemp() with open(os.path.join(workdir, "configuration.yaml"), "wb") as f: f.write( b"# Home Assistant configuration\n" b"homeassistant:\n" b" name: Home\n" b" latitude: !secret home_latitude\n" b"automation: !include automations.yaml\n" ) with open(os.path.join(workdir, "automations.yaml"), "wb") as f: f.write( b"# Automations\n" b"- alias: Morning lights\n" b" trigger:\n" b" - platform: time\n" b" at: \"07:00:00\"\n" b" action:\n" b" - service: light.turn_on\n" ) with open(os.path.join(workdir, "secrets.yaml"), "wb") as f: f.write(b"home_latitude: 52.3676\n") config = yamlrocks.load( os.path.join(workdir, "configuration.yaml"), option=yamlrocks.OPT_INCLUDES | yamlrocks.OPT_SECRETS, ) config["homeassistant"]["name"] # 'Home' config["homeassistant"]["latitude"] # 52.3676 (resolved from secrets.yaml) config["automation"][0]["alias"] # 'Morning lights' ``` -------------------------------- ### Upgrade YAML Document Example Source: https://yaml.rocks/reference/api Demonstrates upgrading a YAML string using the yamlrocks library. ```python import yamlrocks source = """ enabled: yes mode: on """ yamlrocks.upgrade(source) # b'%YAML 1.2\n---\nenabled: true\nmode: true\n' ``` -------------------------------- ### Install YAMLRocks via package managers Source: https://yaml.rocks/getting-started/installation Use your preferred package manager to install the pre-built wheel automatically. ```bash uv add yamlrocks ``` ```bash pip install yamlrocks ``` ```bash poetry add yamlrocks ``` -------------------------------- ### Install YAMLRocks in a virtual environment Source: https://yaml.rocks/getting-started/installation Recommended workflow for isolating the installation within a project-specific virtual environment. ```bash python -m venv .venv source .venv/bin/activate # Windows: .venv\Scripts\activate pip install yamlrocks ``` -------------------------------- ### Verify YAMLRocks installation Source: https://yaml.rocks/getting-started/installation Run this script to confirm the extension is loaded and correctly handles parsing and emitting YAML. ```python import yamlrocks source = """ name: yamlrocks fast: true version: [1, 2] """ # Parse YAML into native Python objects. config = yamlrocks.loads(source) print(config) # {'name': 'yamlrocks', 'fast': True, 'version': [1, 2]} # Emit Python objects back to YAML. dumps returns bytes. print(yamlrocks.dumps(config).decode()) # name: yamlrocks # fast: true # version: # - 1 # - 2 ``` -------------------------------- ### Emitting YAML with Formatting Options Source: https://yaml.rocks/reference/options Examples of using emission flags to control flow style and document markers. ```python import yamlrocks yamlrocks.dumps({"a": [1, 2]}, option=yamlrocks.OPT_FLOW_STYLE) # b'{a: [1, 2]}\n' ``` ```python import yamlrocks yamlrocks.dumps({"a": 1}, option=yamlrocks.OPT_EXPLICIT_START | yamlrocks.OPT_EXPLICIT_END) # b'---\na: 1\n...\n' ``` -------------------------------- ### Run Coverage Analysis Source: https://yaml.rocks/contributing Install necessary tools and execute the coverage suite to measure line coverage across Rust and Python tests. ```bash rustup component add llvm-tools-preview # one-time: the llvm coverage tools cargo install cargo-llvm-cov # one-time just coverage # instrument, run both suites, print a summary ``` -------------------------------- ### Run Fuzzing Targets Source: https://yaml.rocks/contributing Commands to install and execute fuzzing targets using cargo-fuzz and just. ```bash cargo install cargo-fuzz # once; needs a nightly toolchain just fuzz 60 # fuzz `parse` for 60s (the default target) just fuzz 60 differential # fuzz any target by name ``` -------------------------------- ### Install YAMLRocks with numpy support Source: https://yaml.rocks/getting-started/installation Install numpy alongside YAMLRocks to enable serialization of numpy arrays and scalars. ```bash pip install yamlrocks numpy ``` -------------------------------- ### Initialize development environment Source: https://yaml.rocks/contributing Commands to sync dependencies, activate the virtual environment, and build the project extension. ```bash # Install all development dependencies into a managed virtual environment. uv sync # Activate it so `just` (shipped as a dev dependency) is on PATH. source .venv/bin/activate # Build and install the extension (release mode; rerun after Rust changes). just develop ``` -------------------------------- ### Load split configuration from disk Source: https://yaml.rocks/guides/includes Demonstrates building a temporary configuration tree and loading it using the load function with OPT_INCLUDES. ```python import os import tempfile import yamlrocks config = tempfile.mkdtemp() with open(os.path.join(config, "configuration.yaml"), "wb") as handle: handle.write( b"name: home\n" b"automation: !include automations.yaml\n" b"sensors: !include_dir_list sensors\n" ) with open(os.path.join(config, "automations.yaml"), "wb") as handle: handle.write(b"- alias: night\n trigger: time\n") os.mkdir(os.path.join(config, "sensors")) for name, body in (("a.yaml", b"name: A\n"), ("b.yaml", b"name: B\n")): with open(os.path.join(config, "sensors", name), "wb") as handle: handle.write(body) # `load` infers include_dir from the file's own directory. data = yamlrocks.load( os.path.join(config, "configuration.yaml"), option=yamlrocks.OPT_INCLUDES, ) assert data["automation"] == [{"alias": "night", "trigger": "time"}] assert data["sensors"] == [{"name": "A"}, {"name": "B"}] ``` -------------------------------- ### Initialize and run real-world tests Source: https://yaml.rocks/verification/real-world-corpus Initializes the git submodules and executes the full real-world test suite. ```bash git submodule update --init uv run pytest tests/realworld -m realworld ``` -------------------------------- ### Serialize YAML to JSON Source: https://yaml.rocks/reference/api Example of converting a YAML string to JSON bytes. ```python import yamlrocks source = """ name: app ports: [80, 443] """ yamlrocks.to_json(yamlrocks.loads(source)) # b'{"name":"app","ports":[80,443]}' ``` -------------------------------- ### Load Home Assistant configuration from path Source: https://yaml.rocks/recipes/home-assistant Loads a configuration file while resolving includes and secrets relative to the file's directory. ```python import yamlrocks config = yamlrocks.load( "/config/configuration.yaml", option=yamlrocks.OPT_INCLUDES | yamlrocks.OPT_SECRETS, ) ``` -------------------------------- ### Opting into YAML 1.1 and upgrading legacy files Source: https://yaml.rocks/comparisons/vs-pyyaml Shows how to enable legacy YAML 1.1 parsing behavior and use the upgrade utility for migration. ```python import yamlrocks yamlrocks.loads(b"enabled: yes", option=yamlrocks.OPT_YAML_1_1) # {'enabled': True} yamlrocks.upgrade(b"enabled: yes\nmode: on\n") # b'%YAML 1.2\n---\nenabled: true\nmode: true\n' ``` -------------------------------- ### Identify unquoted template errors Source: https://yaml.rocks/guides/loading Example of a common mistake where an unquoted template is interpreted as a mapping key. ```yaml state: { { states('sensor.x') } } # YAML sees a mapping used as a key ``` -------------------------------- ### Run performance benchmarks Source: https://yaml.rocks/comparisons/vs-strictyaml Command to execute the comparison benchmark script on local hardware. ```bash python bench/compare.py ``` -------------------------------- ### Run real-world configuration tests Source: https://yaml.rocks/contributing Initializes git submodules and executes tests against large public configuration files to ensure parsing and round-trip integrity. ```bash git submodule update --init # fetch the config repos once uv run --no-sync pytest tests/realworld -m realworld # run just this category ``` -------------------------------- ### Retrieving Node Range Information Source: https://yaml.rocks/guides/annotated Shows how to access the start and end line/column coordinates for a specific node in the parsed data. ```python import yamlrocks data = yamlrocks.loads(b"key: value\nbroad: x\n", option=yamlrocks.OPT_ANNOTATED) key = list(data)[1] # the 'broad' key (key.__line__, key.__column__) # (2, 1) (key.__end_line__, key.__end_column__) # (2, 6) (just past 'broad') ``` -------------------------------- ### Load YAML data Source: https://yaml.rocks/getting-started/migrating-from-ruamel Demonstrates the difference between ruamel.yaml's instance-based configuration and YAMLRocks's per-call options. ```python from ruamel.yaml import YAML yaml = YAML(typ="safe") data = yaml.load("name: app\nport: 8080") ``` ```python # yamlrocks import yamlrocks source = """ name: app port: 8080 """ data = yamlrocks.loads(source) # {'name': 'app', 'port': 8080} ``` -------------------------------- ### Retrieve source location spans with range() Source: https://yaml.rocks/guides/round-trip The range() method returns a 1-based four-tuple representing the start and end lines and columns of a document or node. ```python import yamlrocks doc = yamlrocks.loads( b"# header\nname: app # inline\nport: 8080\n", option=yamlrocks.OPT_ROUND_TRIP, ) doc.range() # (2, 1, 3, 11) ``` ```python doc["name"] # 'app' ``` -------------------------------- ### Track originating files with !include Source: https://yaml.rocks/guides/annotated Demonstrates how to use OPT_ANNOTATED and OPT_INCLUDES to track the source file path for nodes loaded via !include. ```python import os import tempfile import yamlrocks config = tempfile.mkdtemp() with open(os.path.join(config, "configuration.yaml"), "wb") as handle: handle.write(b"automation: !include automations.yaml\n") with open(os.path.join(config, "automations.yaml"), "wb") as handle: handle.write(b"- alias: night\n trigger: time\n") data = yamlrocks.load( os.path.join(config, "configuration.yaml"), option=yamlrocks.OPT_ANNOTATED | yamlrocks.OPT_INCLUDES, ) # The included list and its items report the file they came from. assert data["automation"].__file__.endswith("automations.yaml") assert data["automation"][0].__file__.endswith("automations.yaml") ``` -------------------------------- ### Format YAML comments Source: https://yaml.rocks/guides/yaml-style Place comments on their own line above the target element, using the same indentation level. Start the comment text with a capital letter and a single space after the hash symbol. ```yaml # Tumble this one until it shines agate: stage: rough ``` -------------------------------- ### Emit and save YAML documents Source: https://yaml.rocks/recipes/config-editor Demonstrates in-memory serialization and filesystem persistence using the round-trip option. ```python doc = yamlrocks.loads(source, option=yamlrocks.OPT_ROUND_TRIP) doc["server"]["port"] = 9090 emitted = yamlrocks.dumps(doc) # bytes, identical to doc.to_yaml() emitted == doc.to_yaml() # True ``` ```python import yamlrocks doc = yamlrocks.load("config.yaml", option=yamlrocks.OPT_ROUND_TRIP) doc["server"]["port"] = 9090 doc.save() # overwrite config.yaml in place doc.save("config.new.yaml") # or write a copy, leaving the original ``` -------------------------------- ### Load and edit split YAML configurations Source: https://yaml.rocks/guides/includes Use OPT_INCLUDES to load split files and OPT_ROUND_TRIP to modify and write back specific include files. ```python import yamlrocks # Read a real split configuration. data = yamlrocks.load("/config/configuration.yaml", option=yamlrocks.OPT_INCLUDES) # Edit and write back only the changed include files. doc = yamlrocks.load( "/config/configuration.yaml", option=yamlrocks.OPT_ROUND_TRIP | yamlrocks.OPT_INCLUDES, ) doc["automation"][0]["trigger"] = "state" yamlrocks.dump_includes(doc, include_dir="/config") ``` -------------------------------- ### Common task runner recipes Source: https://yaml.rocks/contributing List of common commands available via the 'just' task runner for building, testing, and checking the project. ```bash just # list every recipe just develop # build the extension (rerun after Rust changes) just test # run the Python suite (just test -k anchors to filter) just check # the full local gate: build, lint, types, clippy, tests, docs ``` -------------------------------- ### Run Individual Linters and Formatters Source: https://yaml.rocks/contributing Commands to execute specific linting, type checking, and formatting tools. ```bash just lint # ruff check + ruff format --check (Python lint + format) just typecheck # mypy and ty (Python typing) just clippy # cargo clippy --all-targets -D warnings (Rust lint) just fmt # auto-format Python and Rust in place just spellcheck # codespell ``` -------------------------------- ### Load YAML with default annotations Source: https://yaml.rocks/guides/annotated Demonstrates loading YAML data with OPT_ANNOTATED to wrap mappings, sequences, and string scalars in annotated types. ```python import yamlrocks data = yamlrocks.loads( b"server:\n host: localhost\n port: 8080\n", option=yamlrocks.OPT_ANNOTATED, ) type(data).__name__ # 'YAMLRocksAnnotatedDict' next(iter(data)).__line__ # 1 (the `server` key's own line) type(data["server"]["host"]).__name__ # 'YAMLRocksAnnotatedStr' type(data["server"]["port"]).__name__ # 'int' (plain by default) ``` -------------------------------- ### Loading YAML with annotations Source: https://yaml.rocks/recipes/home-assistant Use the OPT_ANNOTATED and OPT_ANNOTATE_NUMBERS flags to enable location tracking for dictionary, list, string, and numeric nodes. ```python import yamlrocks data = yamlrocks.loads( b"http:\n server_port: 8123\n", option=yamlrocks.OPT_ANNOTATED | yamlrocks.OPT_ANNOTATE_NUMBERS, ) data["http"]["server_port"].__line__ # 2 ``` -------------------------------- ### Exercise directory inclusion variants Source: https://yaml.rocks/guides/includes Demonstrates the usage of !include_dir_named, !include_dir_merge_named, and !include_dir_merge_list tags. ```python import os import tempfile import yamlrocks config = tempfile.mkdtemp() with open(os.path.join(config, "configuration.yaml"), "wb") as handle: handle.write( b"lights: !include_dir_named lights\n" b"packages: !include_dir_merge_named packages\n" b"rules: !include_dir_merge_list rules\n" ) os.mkdir(os.path.join(config, "lights")) with open(os.path.join(config, "lights", "kitchen.yaml"), "wb") as handle: handle.write(b"brightness: 80\n") with open(os.path.join(config, "lights", "hall.yaml"), "wb") as handle: handle.write(b"brightness: 40\n") os.mkdir(os.path.join(config, "packages")) with open(os.path.join(config, "packages", "p1.yaml"), "wb") as handle: handle.write(b"sensor_a: 1\n") with open(os.path.join(config, "packages", "p2.yaml"), "wb") as handle: handle.write(b"sensor_b: 2\n") os.mkdir(os.path.join(config, "rules")) with open(os.path.join(config, "rules", "r1.yaml"), "wb") as handle: handle.write(b"- one\n- two\n") with open(os.path.join(config, "rules", "r2.yaml"), "wb") as handle: handle.write(b"- three\n") data = yamlrocks.load( os.path.join(config, "configuration.yaml"), option=yamlrocks.OPT_INCLUDES, ) # _named keys each file by its stem. assert data["lights"] == {"kitchen": {"brightness": 80}, "hall": {"brightness": 40}} # _merge_named folds the per-file mappings into one. assert data["packages"] == {"sensor_a": 1, "sensor_b": 2} # _merge_list concatenates the per-file lists. assert data["rules"] == ["one", "two", "three"] ``` -------------------------------- ### Manage document origins and save paths Source: https://yaml.rocks/guides/round-trip Shows how to handle documents without an origin, save to new locations, and verify file contents after modification. ```python import os import tempfile import yamlrocks work = tempfile.mkdtemp() path = os.path.join(work, "app.yaml") with open(path, "wb") as handle: handle.write(b"# service\nname: app\nport: 8080\n") doc = yamlrocks.load(path, option=yamlrocks.OPT_ROUND_TRIP) assert doc.origin == path doc["port"] = 9090 written = doc.save() assert written == [path] # Only `port` changed; the comment and the rest are intact. assert open(path, "rb").read() == b"# service\nname: app\nport: 9090\n" # Redirect a document to a new path, then save a copy there. other = os.path.join(work, "copy.yaml") doc.set_origin(other) doc.save() assert os.path.exists(other) ``` -------------------------------- ### Execute Code Quality Checks Source: https://yaml.rocks/contributing Commands to run pre-commit hooks and the full local gate check. ```bash just precommit # every pre-commit hook (the set CI runs) just check # the full gate: build, hooks, tests, examples ``` -------------------------------- ### Run the benchmark harness Source: https://yaml.rocks/guides/performance Execute the provided benchmark script to compare YAMLRocks performance against other libraries. ```bash python bench/bench.py ``` -------------------------------- ### Load YAML with Round-Trip Mode Source: https://yaml.rocks/guides/round-trip Initialize a document with round-trip mode enabled to preserve anchor and alias structures. ```python import yamlrocks source = b"""\ defaults: &d retries: 3 timeout: 30 prod: <<: *d timeout: 60 staging: *d """ doc = yamlrocks.loads(source, option=yamlrocks.OPT_ROUND_TRIP) ``` -------------------------------- ### Resolve YAML Anchors, Aliases, and Merge Keys Source: https://yaml.rocks/guides/loading Demonstrates how to use anchors, aliases, and the merge key to reuse and combine mappings within a YAML document. ```python import yamlrocks alias = """ base: &b x: 1 use: *b """ yamlrocks.loads(alias) # {'base': {'x': 1}, 'use': {'x': 1}} merge = """ base: &b {x: 1} use: <<: *b y: 2 """ yamlrocks.loads(merge) # {'base': {'x': 1}, 'use': {'x': 1, 'y': 2}} ``` -------------------------------- ### Parse strings and bytes with loads Source: https://yaml.rocks/guides/loading Demonstrates parsing various input types including bytes, strings, bytearrays, and memoryviews. ```python import yamlrocks yamlrocks.loads(b"key: value") # {'key': 'value'} yamlrocks.loads("count: 42") # {'count': 42} yamlrocks.loads(bytearray(b"x: 1")) # {'x': 1} yamlrocks.loads(memoryview(b"x: 1")) # {'x': 1} ``` -------------------------------- ### Add document markers Source: https://yaml.rocks/guides/dumping Use OPT_EXPLICIT_START and OPT_EXPLICIT_END to include document markers in the output. ```python import yamlrocks yamlrocks.dumps({"a": 1}, option=yamlrocks.OPT_EXPLICIT_START | yamlrocks.OPT_EXPLICIT_END) # b'---\na: 1\n...\n' ``` ```python import yamlrocks yamlrocks.dumps({"b": 1, "a": 2}, option=yamlrocks.OPT_SORT_KEYS | yamlrocks.OPT_INDENT_4) # b'a: 2\nb: 1\n' ``` -------------------------------- ### Configure YAML output with options Source: https://yaml.rocks/getting-started/quick-start Combine integer bit flags using the | operator to customize output formatting. ```python yamlrocks.dumps( {"b": 2, "a": 1}, option=yamlrocks.OPT_SORT_KEYS | yamlrocks.OPT_INDENT_4, ) # b'a: 1\nb: 2\n' ``` -------------------------------- ### Using Options with yamlrocks Source: https://yaml.rocks/reference/options Demonstrates how to combine multiple integer bit flags using the bitwise-OR operator and pass them to the option parameter. ```APIDOC ## Using Options ### Description Options are integer bit flags used to configure serialization and deserialization. They are combined using the bitwise-OR operator `|`. ### Usage ```python import yamlrocks # Example: Sorting keys and setting indentation yamlrocks.dumps({"b": 1, "a": 2}, option=yamlrocks.OPT_SORT_KEYS | yamlrocks.OPT_INDENT_4) ``` ### Notes - Most flags are ignored if they do not apply to the specific call. - Certain combinations are invalid and will raise a `ValueError`. - `loads_all` does not support `OPT_ROUND_TRIP`, `OPT_INCLUDES`, `OPT_SECRETS`, or `OPT_ENV_VAR`. - `OPT_NULL_AS_KEYWORD` and `OPT_NULL_AS_TILDE` cannot be used simultaneously. ``` -------------------------------- ### Create Anchors and Aliases Source: https://yaml.rocks/guides/round-trip Define new anchors and point nodes to them using make_alias, ensuring unique naming and valid reference order. ```python import yamlrocks doc = yamlrocks.loads( b"defaults:\n retries: 3\nprod:\n retries: 5\n", option=yamlrocks.OPT_ROUND_TRIP, ) doc.node["defaults"].anchor = "d" # mark &d doc.node["prod"].make_alias("d") # prod: *d print(doc.to_yaml().decode()) # defaults: &d # retries: 3 # prod: *d ``` -------------------------------- ### Serialize null values Source: https://yaml.rocks/guides/yaml-style Demonstrates default serialization of null and the use of the OPT_NULL_AS_KEYWORD option. ```python import yamlrocks yamlrocks.dumps({"nickname": None}) # b'nickname:\n' ``` ```python import yamlrocks yamlrocks.dumps({"nickname": None}, option=yamlrocks.OPT_NULL_AS_KEYWORD) # b'nickname: null\n' ``` -------------------------------- ### Accessing source provenance metadata Source: https://yaml.rocks/guides/annotated Demonstrates using __source_tag__ and __source_target__ to identify the origin of configuration values, including the use of convenience predicates like is_secret. ```python import os import tempfile import yamlrocks workdir = tempfile.mkdtemp() with open(os.path.join(workdir, "secrets.yaml"), "w") as f: f.write("api_key: s3cr3t\n") with open(os.path.join(workdir, "configuration.yaml"), "w") as f: f.write("api_key: !secret api_key\ntitle: My App\n") opt = yamlrocks.OPT_ANNOTATED | yamlrocks.OPT_SECRETS | yamlrocks.OPT_INCLUDES data = yamlrocks.load(os.path.join(workdir, "configuration.yaml"), option=opt) data["api_key"].is_secret # True (from `api_key: !secret api_key`) data["api_key"].__source_tag__ # '!secret' data["api_key"].__source_target__ # 'api_key' (the directive's argument) data["title"].__source_tag__ # None (a plain inline value) ``` -------------------------------- ### Accessing Source Metadata with OPT_ANNOTATED Source: https://yaml.rocks/guides/annotated Demonstrates loading YAML with annotation enabled and accessing line and column attributes on the resulting objects. ```python import yamlrocks data = yamlrocks.loads( b"name: app\nserver:\n host: localhost\n port: 8080\n", option=yamlrocks.OPT_ANNOTATED, ) isinstance(data, dict) # True (a real dict subclass) data.__line__ # 1 data.__column__ # 1 data["server"].__line__ # 3 (the mapping body starts here) data["server"]["host"].__line__ # 3 data["server"]["host"].__column__ # 9 ``` -------------------------------- ### Use flow style Source: https://yaml.rocks/guides/dumping Enable OPT_FLOW_STYLE to emit YAML in a compact, JSON-like format. ```python import yamlrocks yamlrocks.dumps({"a": [1, 2]}) # b'a:\n - 1\n - 2\n' yamlrocks.dumps({"a": [1, 2]}, option=yamlrocks.OPT_FLOW_STYLE) # b'{a: [1, 2]}\n' ``` -------------------------------- ### Configure Null Value Styles Source: https://yaml.rocks/guides/dumping Use OPT_NULL_AS_KEYWORD or OPT_NULL_AS_TILDE to specify how null values are represented in the output. ```python import yamlrocks yamlrocks.dumps({"a": None, "b": None}) # b'a:\nb:\n' yamlrocks.dumps({"a": None, "b": None}, option=yamlrocks.OPT_NULL_AS_KEYWORD) # b'a: null\nb: null\n' yamlrocks.dumps({"a": None}, option=yamlrocks.OPT_NULL_AS_TILDE) # b'a: ~\n' ``` -------------------------------- ### Configuring Datetime Output Source: https://yaml.rocks/guides/dumping Use flags like OPT_OMIT_MICROSECONDS, OPT_NAIVE_UTC, and OPT_UTC_Z to customize timestamp formatting. ```python import yamlrocks import datetime dt = datetime.datetime( 2026, 6, 5, 12, 30, 45, 123456, tzinfo=datetime.timezone.utc ) yamlrocks.dumps(dt, option=yamlrocks.OPT_OMIT_MICROSECONDS | yamlrocks.OPT_UTC_Z) # b'2026-06-05T12:30:45Z\n' naive = datetime.datetime(2026, 6, 5, 12, 30, 45) yamlrocks.dumps(naive) # b'2026-06-05T12:30:45\n' yamlrocks.dumps(naive, option=yamlrocks.OPT_NAIVE_UTC | yamlrocks.OPT_UTC_Z) # b'2026-06-05T12:30:45Z\n' ``` -------------------------------- ### Build YAMLRocks from source Source: https://yaml.rocks/getting-started/installation Required for platforms without pre-built wheels or when contributing to the project. Requires a Rust toolchain and maturin. ```bash git clone https://github.com/frenck/yamlrocks cd yamlrocks pip install maturin maturin develop --release ``` -------------------------------- ### Load YAML 1.1 with OPT_YAML_1_1 Source: https://yaml.rocks/guides/yaml-11-vs-12 Use the OPT_YAML_1_1 flag to parse documents using strict YAML 1.1 semantics. ```python import yamlrocks yamlrocks.loads(b"feature: on", option=yamlrocks.OPT_YAML_1_1) # {'feature': True} ``` -------------------------------- ### Load YAML with YAMLRocks Source: https://yaml.rocks/comparisons/vs-strictyaml Demonstrates loading a YAML list of countries using YAMLRocks, which correctly interprets 'NO' as a string rather than a boolean. ```python import yamlrocks yamlrocks.loads(b"countries: [NO, SE, DK]") # {'countries': ['NO', 'SE', 'DK']} strings, not [False, 'SE', 'DK'] ``` -------------------------------- ### Asynchronous YAML Loading Source: https://yaml.rocks/reference/api Demonstrates using async_load to read and parse YAML files without blocking the asyncio event loop. ```python import yamlrocks async def read_config(path): return await yamlrocks.async_load(path, option=yamlrocks.OPT_INCLUDES) ``` -------------------------------- ### Load split configuration from bytes Source: https://yaml.rocks/guides/includes Uses the loads function to parse raw bytes, requiring an explicit include_dir to resolve relative paths. ```python raw = open(os.path.join(config, "configuration.yaml"), "rb").read() data = yamlrocks.loads(raw, option=yamlrocks.OPT_INCLUDES, include_dir=config) assert data["sensors"] == [{"name": "A"}, {"name": "B"}] ``` -------------------------------- ### Merge included files with << Source: https://yaml.rocks/guides/includes Use the merge key with !include to fold external mappings into the current document. Local keys take precedence over included defaults. ```python import os import tempfile import yamlrocks config = tempfile.mkdtemp() with open(os.path.join(config, "defaults.yaml"), "wb") as handle: handle.write(b"retries: 3\ntimeout: 30\n") with open(os.path.join(config, "service.yaml"), "wb") as handle: handle.write(b"service:\n <<: !include defaults.yaml\n timeout: 60\n") data = yamlrocks.load( os.path.join(config, "service.yaml"), option=yamlrocks.OPT_INCLUDES, ) # The included defaults are merged in; the local `timeout` overrides. assert data["service"] == {"retries": 3, "timeout": 60} ``` -------------------------------- ### Run project tests Source: https://yaml.rocks/contributing Executes the test suite with optional filtering or shell-level memory guards to prevent resource exhaustion. ```bash just test # or: uv run --no-sync pytest just test -k anchors # extra args pass straight through to pytest # with an explicit shell guard: timeout 120 bash -c 'ulimit -v 3000000; uv run --no-sync pytest' ``` -------------------------------- ### loads(data, /, *, ...) Source: https://yaml.rocks/reference/api Parses the first YAML document from the provided data and returns native Python objects. ```APIDOC ## loads(data, /, *, ...) ### Description Parses the first YAML document from `data` and returns native Python objects. Empty input returns `None`. ### Signature `def loads(data: bytes | bytearray | memoryview | str, /, *, option: int | None = None, include_dir: str | os.PathLike[str] | None = None, schema: Any | None = None, schema_resolver: Callable[[str], Any | None] | None = None, tag_handler: Callable[[str, Any], Any] | None = None, tags: dict[str, Callable[[Any], Any]] | None = None, root_path: str | os.PathLike[str] | None = None, on_missing_secret: Callable[[str, str | None, int], None] | None = None, on_missing_env_var: Callable[[str, str | None, int], None] | None = None) -> Any` ### Parameters - **data** (bytes | bytearray | memoryview | str) - Required - The YAML input data. - **option** (int) - Optional - A bitwise-OR of `OPT_*` flags. - **include_dir** (str | os.PathLike) - Optional - Base directory for `!include` resolution. - **root_path** (str | os.PathLike) - Optional - The on-disk path the in-memory data represents. - **schema** (Any) - Optional - A JSON Schema dict or "auto" for in-file validation. - **schema_resolver** (Callable) - Optional - Used with `schema="auto"` to resolve references. - **tags** (dict) - Optional - Mapping of tags to functions. - **tag_handler** (Callable) - Optional - Catch-all callback for tags not in `tags`. - **on_missing_secret** (Callable) - Optional - Callback for undefined `!secret` nodes. - **on_missing_env_var** (Callable) - Optional - Callback for undefined `!env_var` nodes. ``` -------------------------------- ### Perform Dependency Audits Source: https://yaml.rocks/contributing Commands to run security and supply-chain audits for project dependencies. ```bash just audit # all ecosystems at once just audit-rust # audit Rust dependencies just audit-python # audit Python dependencies just audit-docs # audit documentation dependencies ``` -------------------------------- ### Execute Performance Benchmarks Source: https://yaml.rocks/contributing Run comparative benchmarks against other libraries or profile internal operations using CodSpeed. ```bash just bench # comparison report vs other libraries just codspeed # YAMLRocks's own operations (local walltime; CI instruments) ``` -------------------------------- ### Configure YAML 1.1 schema parsing Source: https://yaml.rocks/reference/options Demonstrates how OPT_YAML_1_1 changes the interpretation of boolean-like strings compared to the default YAML 1.2 behavior. ```python import yamlrocks yamlrocks.loads(b"a: yes") # {'a': 'yes'} yamlrocks.loads(b"a: yes", option=yamlrocks.OPT_YAML_1_1) # {'a': True} ``` -------------------------------- ### loads_all(data, /, *, ...) Source: https://yaml.rocks/reference/api Parses every --- separated document in the stream into a list. ```APIDOC ## loads_all(data, /, *, ...) ### Description Parses every `---`-separated document in the stream into a list, one entry per document. ### Signature `def loads_all(data: bytes | bytearray | memoryview | str, /, *, option: int | None = None, tag_handler: Callable[[str, Any], Any] | None = None, tags: dict[str, Callable[[Any], Any]] | None = None) -> list[Any]` ### Parameters - **data** (bytes | bytearray | memoryview | str) - Required - The YAML input stream. - **option** (int) - Optional - A bitwise-OR of `OPT_*` flags. - **tags** (dict) - Optional - Mapping of tags to functions. - **tag_handler** (Callable) - Optional - Catch-all callback for tags not in `tags`. ``` -------------------------------- ### Using the PyYAML compatibility shim Source: https://yaml.rocks/comparisons/vs-pyyaml The shim provides safe_load and safe_dump functions that mimic PyYAML behavior for easier migration. ```python import yamlrocks.compat as yaml yaml.safe_load(b"a: 1") # {'a': 1} yaml.safe_dump({"a": 1}) # 'a: 1\n' (a str, matching PyYAML) ``` -------------------------------- ### Define block style sequences Source: https://yaml.rocks/guides/yaml-style List items should be placed on their own lines, indented one level under the parent key. ```yaml # Good climbing_rack: - cams - nuts - quickdraws ``` -------------------------------- ### async_loads_all(data, ...) Source: https://yaml.rocks/reference/api Asynchronously parses a multi-document YAML stream from memory. ```APIDOC ## async_loads_all(data, ...) ### Description Asynchronously parses a multi-document YAML stream provided as an in-memory string or bytes. ### Parameters - **data** (str/bytes) - Required - The YAML data to parse. - **...** (kwargs) - Optional - Same keyword arguments as the synchronous `loads_all` function. ``` -------------------------------- ### async_load(source, ...) Source: https://yaml.rocks/reference/api Asynchronously reads and parses a YAML file. ```APIDOC ## async_load(source, ...) ### Description Asynchronously reads a file from the provided source and parses the YAML content, offloading both the file I/O and the parsing to a worker thread. ### Parameters - **source** (file-like) - Required - The file source to read from. - **...** (kwargs) - Optional - Same keyword arguments as the synchronous `load` function. ``` -------------------------------- ### Handle empty documents Source: https://yaml.rocks/guides/loading Shows that empty input or input containing only comments returns None. ```python import yamlrocks print(yamlrocks.loads(b"")) # None print(yamlrocks.loads(b"# just a comment")) # None ``` -------------------------------- ### Compare Octal Integer Parsing Source: https://yaml.rocks/guides/yaml-11-vs-12 Demonstrates how leading-zero octal numbers are parsed as strings in YAML 1.2 but as integers in YAML 1.1. ```python import yamlrocks yamlrocks.loads(b"perm: 0777") # {'perm': '0777'} yamlrocks.loads(b"perm: 0777", option=yamlrocks.OPT_YAML_1_1) # {'perm': 511} ``` -------------------------------- ### Use the YAMLRocks compatibility shim Source: https://yaml.rocks/getting-started/migrating-from-pyyaml Alias the compat module as yaml to maintain compatibility with existing PyYAML code. ```python from yamlrocks import compat as yaml data = yaml.safe_load("name: app\nport: 8080") # {'name': 'app', 'port': 8080} text = yaml.safe_dump(data) # 'name: app\nport: 8080\n' (a str, like PyYAML) ``` -------------------------------- ### async_load_all(source, ...) Source: https://yaml.rocks/reference/api Asynchronously reads and parses a multi-document YAML file. ```APIDOC ## async_load_all(source, ...) ### Description Asynchronously reads and parses a multi-document YAML file, offloading the operation to a worker thread. ### Parameters - **source** (file-like) - Required - The file source to read from. - **...** (kwargs) - Optional - Same keyword arguments as the synchronous `load_all` function. ``` -------------------------------- ### Configure PyYAML Compatibility Modes Source: https://yaml.rocks/getting-started/compatibility Demonstrates the difference in scalar parsing between YAML 1.1 and PyYAML compatibility modes. ```python import yamlrocks source = """ y: 2 on: 5 """ yamlrocks.loads(source, option=yamlrocks.OPT_YAML_1_1) # {True: 5} yamlrocks.loads(source, option=yamlrocks.OPT_PYYAML_COMPAT) # {'y': 2, True: 5} ``` -------------------------------- ### load_all(source, /, *, option=None, tag_handler=None, tags=None) Source: https://yaml.rocks/reference/api Reads a multi-document file or stream and returns every document as a list. ```APIDOC ## load_all ### Description The file-oriented counterpart to `loads_all`. Reads a multi-document file or stream and returns every document as a list. ### Signature `def load_all(source: str | os.PathLike[str] | Any, /, *, option: int | None = None, tag_handler: Callable[[str, Any], Any] | None = None, tags: dict[str, Callable[[Any], Any]] | None = None) -> list[Any]` ### Parameters - **source** (str | os.PathLike[str] | Any) - Required - The source file or stream to read. - **option** (int | None) - Optional - Configuration option. - **tag_handler** (Callable[[str, Any], Any] | None) - Optional - Custom tag handler function. - **tags** (dict[str, Callable[[Any], Any]] | None) - Optional - Dictionary of tag handlers. ``` -------------------------------- ### Write YAML to a file Source: https://yaml.rocks/guides/dumping Demonstrates writing a dictionary to a file path or an open file object using the dump method. ```python import yamlrocks yamlrocks.dump({"name": "app", "port": 8080}, "config.yaml") with open("config.yaml", "wb") as f: yamlrocks.dump({"name": "app", "port": 8080}, f) ``` -------------------------------- ### Sort mapping keys Source: https://yaml.rocks/guides/dumping Enable OPT_SORT_KEYS to emit mapping keys in alphabetical order instead of insertion order. ```python import yamlrocks yamlrocks.dumps({"b": 1, "a": 2}) # b'b: 1\na: 2\n' yamlrocks.dumps({"b": 1, "a": 2}, option=yamlrocks.OPT_SORT_KEYS) # b'a: 2\nb: 1\n' ``` -------------------------------- ### Enable recursive directory inclusion Source: https://yaml.rocks/guides/includes Uses OPT_INCLUDE_DIR_RECURSIVE to descend into subdirectories during inclusion. ```python data = yamlrocks.load( os.path.join(config, "configuration.yaml"), option=yamlrocks.OPT_INCLUDES | yamlrocks.OPT_INCLUDE_DIR_RECURSIVE, ) ``` -------------------------------- ### Dump YAML data Source: https://yaml.rocks/getting-started/migrating-from-ruamel Shows how to output YAML data to a stream or as bytes using ruamel.yaml versus YAMLRocks. ```python import sys yaml.dump(data, sys.stdout) ``` ```python # yamlrocks import sys import yamlrocks sys.stdout.write(yamlrocks.dumps({"name": "app", "port": 8080}).decode()) # name: app # port: 8080 ``` -------------------------------- ### Core YAML round-trip edit loop Source: https://yaml.rocks/recipes/config-editor Demonstrates the full cycle of loading, reading, modifying, and re-emitting a YAML document while maintaining original formatting. ```python import yamlrocks source = b"""# Service configuration server: host: localhost # bind address port: 8080 features: - logging - metrics """ doc = yamlrocks.loads(source, option=yamlrocks.OPT_ROUND_TRIP) # Read values like a dict / list. doc["server"]["host"] # 'localhost' # Write values; only what you touch changes. doc["server"]["port"] = 9090 # Emit the bytes, comments and layout intact. doc.to_yaml() # b'# Service configuration\nserver:\n host: localhost # bind address\n port: 9090\n...' ``` -------------------------------- ### Registering custom tags with YAMLRocksTags Source: https://yaml.rocks/reference/api Shows how to use the YAMLRocksTags registry and the register decorator to handle custom YAML tags. ```python import yamlrocks tags = yamlrocks.YAMLRocksTags() @tags.register("!vec") def make_vec(value): return tuple(value) yamlrocks.loads(b"p: !vec [1, 2]", tags=tags) # {'p': (1, 2)} ``` -------------------------------- ### yamlrocks.compat Source: https://yaml.rocks/reference/api The compatibility shim provides a drop-in replacement for PyYAML, exposing standard loading and dumping functions. ```APIDOC ## yamlrocks.compat ### Description A drop-in replacement for PyYAML to facilitate gradual migration. It provides standard YAML processing functions. ### Functions - **safe_load(stream)**: Parses a YAML stream. - **safe_load_all(stream)**: Parses all YAML documents in a stream. - **safe_dump(data, stream=None)**: Serializes data to YAML. - **safe_dump_all(documents, stream=None)**: Serializes multiple documents to YAML. - **load(stream)**: Standard load function. - **load_all(stream)**: Standard load all function. - **dump(data, stream=None)**: Standard dump function. - **dump_all(documents, stream=None)**: Standard dump all function. ### Example ```python from yamlrocks import compat compat.safe_load("a: 1") # {'a': 1} compat.safe_dump({"b": 2, "a": 1}) # 'a: 1\nb: 2\n' ``` ``` -------------------------------- ### Handle missing secrets during loading Source: https://yaml.rocks/guides/tags Use callbacks or warning flags to collect missing secret information instead of raising an error. ```python import yamlrocks source = """ a: !secret one b: !secret two """ missing = [] data = yamlrocks.loads( source, option=yamlrocks.OPT_SECRETS, include_dir=".", on_missing_secret=lambda name, file, line: missing.append((name, line)), ) # data == {'a': None, 'b': None} # missing == [('one', 1), ('two', 2)] ``` ```python import yamlrocks source = """ a: !secret one b: !secret two """ data = yamlrocks.loads( source, option=yamlrocks.OPT_SECRETS | yamlrocks.OPT_SECRET_NOT_FOUND_WARN, include_dir=".", ) # data == {'a': None, 'b': None} # logs: secret 'one' is not defined in any secrets.yaml at :1 # logs: secret 'two' is not defined in any secrets.yaml at :2 ``` -------------------------------- ### Inspect a document view Source: https://yaml.rocks/guides/round-trip Shows how to use navigation methods on a YAMLRocksDocumentView to inspect sub-trees or extract snapshots. ```python view = doc["server"] view.to_dict() # {'host': 'example.com', 'ports': [80, 8443]} view.unwrap() # same plain dict/list snapshot view.keys() # ['host', 'ports'] ``` -------------------------------- ### Asynchronous file loading with async_load Source: https://yaml.rocks/guides/loading Load YAML data directly from files asynchronously to avoid blocking on slow disk I/O. ```python import asyncio import yamlrocks with open("config.yaml", "w") as f: f.write("name: app\nport: 8080\n") async def main(): return await yamlrocks.async_load("config.yaml") asyncio.run(main()) # {'name': 'app', 'port': 8080} ``` -------------------------------- ### Ensure 1.1-safe serialization Source: https://yaml.rocks/reference/options Shows how OPT_YAML_1_1 forces quoting of strings that would be interpreted as non-strings in YAML 1.1, ensuring compatibility. ```python import yamlrocks yamlrocks.dumps({"elapsed": "10:20:30"}) # b'elapsed: 10:20:30\n' yamlrocks.dumps({"elapsed": "10:20:30"}, option=yamlrocks.OPT_YAML_1_1) # b'elapsed: "10:20:30"\n' ``` -------------------------------- ### Preview changes with dump_includes_map Source: https://yaml.rocks/guides/includes Generate a mapping of paths to bytes representing pending changes without writing to the filesystem. ```python changes = yamlrocks.dump_includes_map(doc) # {'.../automations.yaml': b'- alias: night\n trigger: state\n'} assert any(path.endswith("automations.yaml") for path in changes) ``` -------------------------------- ### Save YAMLRocksDocument to disk Source: https://yaml.rocks/guides/round-trip Demonstrates loading a document, modifying a value, and saving it back to its original file path. ```python import yamlrocks doc = yamlrocks.load("/config/app.yaml", option=yamlrocks.OPT_ROUND_TRIP) doc["port"] = 9090 doc.origin # '/config/app.yaml' doc.save() # ['/config/app.yaml'] - written in place ``` -------------------------------- ### Configure two-space indentation Source: https://yaml.rocks/guides/yaml-style Use two spaces per level for consistent hierarchy. Avoid tabs and maintain uniform indentation depth. ```yaml boulder: grade: V4 name: Sunlit Slab ```