Ordered YAML (oyaml)
oyaml is a drop-in replacement for PyYAML designed to preserve dictionary ordering during YAML loading and dumping. It supports both Python 2 and Python 3 by patching the underlying PyYAML library. The current version is 1.1, with releases occurring infrequently, primarily for compatibility updates with newer PyYAML versions or test suite improvements.
Warnings
- gotcha For Python 3.7 and later, standard dictionaries (`dict`) inherently preserve insertion order. This reduces the primary benefit of `oyaml` for these Python versions when working with standard `dict`s, though `oyaml` still ensures `OrderedDict`s are used or order is strictly maintained across all operations and Python versions.
- breaking In `oyaml` v0.8, the behavior for `FullLoader` in CPython 3.6+ was changed to deserialize YAML maps into a standard Python `dict` instead of `collections.OrderedDict`. If your application relied on `FullLoader` returning `OrderedDict` on CPython 3.6+ specifically, this change is breaking.
- gotcha Like PyYAML, it is unsafe to use `yaml.load()` with untrusted input due to the potential for arbitrary code execution. Always prefer `yaml.safe_load()` for security.
Install
-
pip install oyaml
Imports
- yaml
import oyaml as yaml
Quickstart
import oyaml as yaml
from collections import OrderedDict
yaml_data = """
key_c: 3
key_a: 1
key_b: 2
"""
# Load YAML preserving order
loaded_dict = yaml.safe_load(yaml_data)
print(f"Loaded dictionary type: {type(loaded_dict)}")
print(f"Loaded dictionary keys order: {list(loaded_dict.keys())}")
# Dump a dictionary with explicit order
ordered_data = OrderedDict([
('first_key', 'value_1'),
('second_key', 'value_2'),
('third_key', 'value_3')
])
dumped_yaml = yaml.safe_dump(ordered_data, sort_keys=False)
print(f"\nDumped YAML with order preserved:\n{dumped_yaml}")