Search code examples
yamlpyyamlruamel.yaml

Define YAML Mapping Recursively


Is there a simple way to define a mapping in yaml in such a way that the value is itself defined within the yaml. E.g.

alice:
  name: Alice

bob:
  manager: *alice 

So that the value that mapped to the mangager key for bob is the alice object, not a string. So that once the file is parsed I can do something like

>>> data = yaml.load(file_path)
>>> alice, bob = data["alice"], data["bob"]
>>> bob.manager is alice
True

Solution

  • You simply need to give the object you want to reference an anchor:

    alice: &alice
      name: Alice
    
    bob:
      manager: *alice