Skip to content
Advertisement

yaml anchors definitions loading in PyYAML

I’m using PyYAML. Is there a way to define a YAML anchor in a way it won’t be a part of the data structure loaded by yaml.load (I can remove “wifi_parm” from the dictionary but looking for a smarter way)?

example.yaml:

JavaScript

load_example.py:

JavaScript

prints:

JavaScript

I need:

JavaScript

Advertisement

Answer

The anchor information in PyYAML is discarded before you get the result from yaml.load(). This is according to the YAML 1.1 specification that PyYAML follows (… anchor names are a serialization detail and are discarded once composing is completed). This has not changed in the YAML 1.2 specification (from 2009). You cannot do this in PyYAML by walking over your result (recursively) and testing what values might be anchors, without extensively modifying the parser.

In my ruamel.yaml (which is YAML 1.2) in round-trip-mode, I preserve the anchors and aliases for anchors that are actually used to alias mappings or sequences (anchors aliases are currently not preserved for scalars, nor are “unused” anchors):

JavaScript

gives:

JavaScript

and you can actually walk the mapping (or recursively the tree) and find the anchor node and delete it, without knowing the keys name.

JavaScript

gives:

JavaScript

doing this generically and recursively (i.e. for anchors and aliases that are anywhere in the tree) is possible as well. The update would be as easy as above, but you would need to keep track of how to delete a key, and this doesn’t have to be a mapping value, it could be a sequence item or a scalar.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement