YAML anchors and aliases and how to disable them
Introduction
In this short post I explain what are YAML aliases and anchors. I then show you how to stop PyYAML from using these when serializing data structures.
While references are absolutely fine to use in YAML files meant for programmatic consumption I find that it sometimes confuses humans, especially if they’ve never seen these before. For this reason I tend to disable anchors and aliases when saving data to YAML files meant for human consumption.
Contents
- YAML aliases and anchors
- When does YAML use anchors and aliases
- YAML dump - don’t use anchors and aliases
- Conclusion
- References
- GitHub repository with resources for this post
YAML aliases and anchors
YAML specification has provision for preserving information about nodes pointing to the same data. This basically means that if you have some data that is referenced in multiple places in your data structure then YAML dumper will:
- add an anchor to the first occurrence
- replace any subsequent occurrences of that data with aliases
Now, how do these anchors and aliases look like?
&id001 - example of an anchor, placed with the first occurrence of data
*id001 - example of an alias, replaces subsequent occurrence Continue reading
.