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.
pip install oyamlVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to import oyaml as `yaml` and use its `safe_load` and `safe_dump` functions. It shows that `oyaml` preserves the order of keys when loading from a YAML string and when dumping an `OrderedDict` to a YAML string, by default, if `sort_keys=False` is used for `safe_dump` with standard dictionaries. For Python versions < 3.7, `safe_load` will return `OrderedDict` instances. For Python 3.7+ with standard `dict`s, while `safe_load` might return a standard `dict`, its order is insertion-ordered.
Consider if `oyaml` is truly necessary for new code on Python 3.7+, or if direct `PyYAML` usage with `sort_keys=False` for dumping (if order matters for output) is sufficient. For cross-version compatibility or explicit `OrderedDict` requirements, `oyaml` remains useful.
Explicitly cast the loaded dictionary to `OrderedDict` if the specific type is required, or ensure your code is robust to handling either `dict` or `OrderedDict` from `FullLoader`.
Replace all instances of `yaml.load()` with `yaml.safe_load()` when processing input from untrusted sources.
Install the oyaml package using pip: `pip install oyaml`
Ensure the YAML file contains the expected key, or use dictionary's `.get()` method with a default value to prevent the error, e.g., `data.get('key_name', default_value)`Ensure that PyYAML version 5.1 or newer is installed, as `FullLoader` was introduced in this version. If `oyaml` is imported as `import oyaml as yaml`, verify `oyaml` is up-to-date and compatible with the desired PyYAML version. Often, `yaml.safe_load()` is sufficient and a safer alternative.